简体   繁体   中英

Collection to string using linq

I have a class

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

List<Person> 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 .)

您可以使用

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM