LINQ 如何按两个列表分组到一个列表
本文关键字:列表 一个 何按两 LINQ | 更新日期: 2023-09-27 18:37:11
我有两个列表,它们都有一个ID(唯一),我只想通过它的唯一属性对它们进行分组,并获得一个包含这两个列表的新列表。
list1 group by list2 -> get list3
这是我的代码:
List<LeadDocumentStatusQuerySequence> list1 =
client.GetLeadDocumentStatusQuerySequence();
List<LeadDocumentStatusQueryDeclarationDetails> list2 =
client.GetLeadDocumentStatusQueryDeclarationDetails();
我需要获取包含两个列表的第三个列表,我想按 ID 分组,但是如何在 LINQ 中编写它?
var both = ...?
提前谢谢。
我不确定这是否是你想要的,但见下文。我假设人是动物的一个子类。
var combinedList = new List<Animal>();
combinedList.AddRange(people);
combinedList.AddRange(animals);
var grouped = combinedList.GroupBy(y => new {y.ID}).ToList();
目前尚不清楚您将如何操作数据,但使用 CompositeCollection 可以是一种将数据组合在一起的方法。它在 WPF 中用于组合要在屏幕上显示的不同集合。
请注意,以下类中的Name
在 C# 编译器意义上没有直接关系,因此两者之间没有直接关联:
void Main()
{
var myAnimals = new List<Animal>() { new Animal() { Name = "Zebra" },
new Animal() { Name = "Cobra" }} ;
var myPeople = new List<Person>() { new Person() { Name = "Snake Pliskin" },
new Person() { Name = "OmegaMan" }};
// Uses System.Windows.Data
var FavoriteThings = new CompositeCollection();
FavoriteThings.Add(myAnimals);
FavoriteThings.Add(myPeople);
}
// Define other methods and classes here
public class Animal
{
public string Name { get; set; }
}
public class Person
{
public string Name { get; set; }
}