开发者

Collection to string using linq

I have a class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }   
}

List<Person&g开发者_StackOverflowt; PersonList = new List<Perso>();
PersonList.Add(new Person() { FirstName = "aa", LastName = "AA" } );
PersonList.Add(new Person() { FirstName = "bb", LastName = "BB" } );

I'd like get a string with a comma separator for the LastName, using Linq, the result look like: AA,BB

Thanks,


If you're using .NET 4:

string lastNames = string.Join(",", PersonList.Select(x => x.LastName));

If you're using .NET 3.5:

string lastNames = string.Join(",", PersonList.Select(x => x.LastName)
                                              .ToArray());

(Basically .NET 4 had some extra overloads added to string.Join.)


You can use

PersonList.Select(p => p.LastName).Aggregate((s1,s2) => s1 + ", " + s2);


To concatenate string items, with separators, you can use String.Join

In .NET 3.5 and below, this takes an array as the second parameter, but in 4.0 it has an overload that takes an IEnumerable<T>, where T in this case is String.

Armed with this information, here's the code you want.

For .NET 3.5:

string result = String.Join(", ",
    (from p in PersonList
     select p.LastName).ToArray());

For .NET 4.0 you can omit the call to ToArray:

string result = String.Join(", ",
    from p in PersonList
    select p.LastName);

If you want to drop the LINQ-syntax and just use the LINQ extension methods, here's the same in that variant:

For .NET 3.5:

string result = String.Join(", ", PersonList.Select(p => p.LastName).ToArray());

For .NET 4.0 you can omit the call to ToArray:

string result = String.Join(", ", PersonList.Select(p => p.LastName));

Note: The 3.5 variants above of course works in 4.0 as well, they did not remove or replace the old method, they just added one for the typical case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜