Job*_*Joy 510 c# linq .net-3.5
是否有任何简单的LINQ表达式将我的整个List<string>集合项连接到string具有分隔符的单个?
如果集合是自定义对象而不是string?想象一下,我需要连接object.Name.
Sed*_*glu 909
在.NET 4.0或更高版本中:
String.Join(delimiter, list);
Run Code Online (Sandbox Code Playgroud)
足够了.
Ali*_*söz 493
通过使用LINQ,这应该工作;
string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));
Run Code Online (Sandbox Code Playgroud)
课程描述:
public class Foo
{
public string Boo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
用法:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我最好的:)
items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
Run Code Online (Sandbox Code Playgroud)
Ale*_*yev 114
这是一个字符串数组:
string.Join(delimiter, array);
Run Code Online (Sandbox Code Playgroud)
这是一个List <string>:
string.Join(delimiter, list.ToArray());
Run Code Online (Sandbox Code Playgroud)
这是一个自定义对象列表:
string.Join(delimiter, list.Select(i => i.Boo).ToArray());
Run Code Online (Sandbox Code Playgroud)
dev*_*.bv 53
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));
Run Code Online (Sandbox Code Playgroud)
Jac*_*itt 24
好问题.我一直在用
List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
string joinedString = string.Join(", ", myStrings.ToArray());
Run Code Online (Sandbox Code Playgroud)
它不是LINQ,但它有效.
您可以简单地使用:
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(string.Join(",", items));
Run Code Online (Sandbox Code Playgroud)
快乐编码!
List<string> strings = new List<string>() { "ABC", "DEF", "GHI" };
string s = strings.Aggregate((a, b) => a + ',' + b);
Run Code Online (Sandbox Code Playgroud)
我认为如果你在扩展方法中定义逻辑,代码将更具可读性:
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(", ");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
389783 次 |
| 最近记录: |