我有一个List<string> list1
,示例值:
var list1 = new List<string>()
{
"123", "1234", "12345",
};
我有一堂课:
public class TestClass {
public string name{ get; set; }
public int count{ get; set; }
}
我有一个
List<TestClass> list2
,示例值:var list2 = new List<TestClass>()
{
new TestClass() { name = "12", count = 0 },
new TestClass() { name = "123", count = 5 },
new TestClass() { name = "1234", count = 20 },
};
我想合并
list1
和list2
,结果应该是:name count
12 0
123 5
1234 20
12345 0
最佳答案
这很好用:
var list1 = new List<string>()
{
"123", "1234", "12345",
};
var list2 = new List<TestClass>()
{
new TestClass() { name = "12", count = 0 },
new TestClass() { name = "123", count = 5 },
new TestClass() { name = "1234", count = 20 },
};
var merged =
list2
.Concat(list1.Select(x => new TestClass() { name = x, count = 0 }))
.GroupBy(x => x.name)
.SelectMany(x => x.Take(1))
.ToList();
它给了我:
关于c# - 如何合并两个不同的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54996588/