Concat all strings inside a List<string> using LINQ
是否有任何简单的linq表达式可以将整个
如果集合是自定义对象而不是
在.NET 4.0或以后的版本:
1 | String.Join(delimiter, list); |
是足够的。
使用LINQ,本应工作;
1 2 3 | string delimiter =","; List<string> items = new List<string>() {"foo","boo","john","doe" }; Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j)); |
描述:类
1 2 3 4 | public class Foo { public string Boo { get; set; } } |
用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Program { static void Main(string[] args) { string delimiter =","; List<Foo> items = new List<Foo>() { new Foo { Boo ="ABC" }, new Foo { Boo ="DEF" }, new Foo { Boo ="GHI" }, new Foo { Boo ="JKL" } }; Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo); Console.ReadKey(); } } |
这是我的最好的:)
1 | items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j) |
这是一个字符串数组:
1 | string.Join(delimiter, array); |
这是一个字符串列表>:<
1 | string.Join(delimiter, list.ToArray()); |
这是一个自定义对象的列表:
1 | string.Join(delimiter, list.Select(i => i.Boo).ToArray()); |
1 2 3 4 5 6 7 8 9 10 11 | using System.Linq; public class Person { string FirstName { get; set; } string LastName { get; set; } } List<Person> persons = new List<Person>(); string listOfPersons = string.Join(",", persons.Select(p => p.FirstName)); |
善的问题。我已经使用
1 2 | List<string> myStrings = new List<string>{"ours","mine","yours"}; string joinedString = string.Join(",", myStrings.ToArray()); |
它不是LINQ的,但它的作品。
我认为,如果你定义的逻辑方法将扩展的代码更可读。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public static class EnumerableExtensions { public static string Join<T>(this IEnumerable<T> self, string separator) { return String.Join(separator, self.Select(e => e.ToString()).ToArray()); } } public class Person { public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return string.Format("{0} {1}", FirstName, LastName); } } // ... List<Person> people = new List<Person>(); // ... string fullNames = people.Join(","); string lastNames = people.Select(p => p.LastName).Join(","); |
1 2 | List<string> strings = new List<string>() {"ABC","DEF","GHI" }; string s = strings.Aggregate((a, b) => a + ',' + b); |
你可以使用简单的:
1 2 3 | List<string> items = new List<string>() {"foo","boo","john","doe" }; Console.WriteLine(string.Join(",", items)); |
快乐编码!
我已经做了这个:使用LINQ
1 2 3 | var oCSP = (from P in db.Products select new { P.ProductName }); string joinedString = string.Join(",", oCSP.Select(p => p.ProductName)); |