csharp-linqmerge

C# Linq合并List中的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

static void Main(string[] args){

List<Person> pList = new List<Person>();

Person person1 = new Person() { FirstName = "john", LastName = "wonder" };
Person person3 = new Person() { FirstName = "john2", LastName = "wonder22" };
Person person4 = new Person() { FirstName = "john2", LastName = "wonder2233" };

pList.Add(person1);
pList.Add(person3);
pList.Add(person4);


var pMergeList= pList.ToLookup(x => x.FirstName).Select(x => x.Aggregate((p1, p2) =>

new Person{
FirstName = p1.FirstName,
LastName = p1.LastName + ";"+ p2.LastName
}
)).ToList();

foreach (var item in pMergeList)
{
Console.WriteLine("FirstName:" + item.FirstName);
Console.WriteLine("LastName:" + item.LastName);

}

Console.Read();
}


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

public string LastName { get; set; }
}


class PersonModel
{
public string FirstName { get; set; }

public string LastNameList { get; set; }
}
欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%