我有一个如下所示的对象集合。
List<Product> productList=new List<Product>();
Product 类的结构如下所示。
public class Product
{
public int Id;
public Product(int id)
{
Id=id;
}
public List<SomeOtherList> t;
}
Product 类包含一些其他列表
public class SomeOtherList
{
private int value;
public SomeOtherList(int val)
{
value=val;
}
}
Product prodOne=new Product(1);
List<SomeOtherList> temp_1=new List<SomeOtherList>();
temp_1.Add(new SomeOtherList(10));
temp_1.Add(new SomeOtherList(20));
temp_1.Add(new SomeOtherList(30));
prodOne.t=temp_1;
Product prodTwo=new Product(2);
List<SomeOtherList> temp_2=new List<SomeOtherList>();
temp_2.Add(new SomeOtherList(100));
temp_2.Add(new SomeOtherList(40));
temp_2.Add(new SomeOtherList(30));
prodTwo.t=temp_2;
Product prodThree=new Product(1);
List<SomeOtherList> temp_3=new List<SomeOtherList>();
temp_3.Add(new SomeOtherList(10));
temp_3.Add(new SomeOtherList(20));
prodThree.t=temp_3;
productList.Add(prodOne);
productList.Add(prodTwo);
productList.Add(prodThree);
我想获得所有产品共有的“SomeOtherList”对象。例如,对于产品 ID 1,我应该将 SomeOtherList 对象 20 作为普通对象。
我编写了以下 LINQ 查询来实现此目的。
List<Product> t=productList
.GroupBy(p => p.Id)
.Where(g => g.Count() == productList.Count)
.Select(x => x.First())
.ToList();
但它并没有给我想要的东西。有人可以指出该查询有什么问题吗?
最佳答案
你想要的是 intersection 当产品是某个特定值(即 1)时,您的 SomeOtherList
之间。
因此,您需要首先选择具有正确 Id
的每个 Product
,然后将它们的 SomeOtherList
连接在一起并按值分组。
为此,我们需要扁平化 Product
的每个SomeOtherList
,我们可以使用SelectMany
来做到这一点
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
单一ID
如果我们只对单个 Id 感兴趣,那么我们可以执行以下操作
var common1 = productList
.Where(product => product.Id == 1)
.SelectMany(product => product.t)
.GroupBy(groupValue => groupValue.value)
.Where(groupValue => groupValue.Count() > 1)
.Select(values => values.First());
这将:
- 根据Id等于1过滤产品
- 将每个产品
SomeOtherList
扁平化为一个 IEnumerable - 根据
SomeOtherList.value
对每个元素进行分组 - 过滤掉任何只有 1 个条目的组,因为我们只想要那些常见的
所有 Id 的
但是,如果我们想获取每个键的所有重复项的列表,那么我们可以执行与单个 ID 相同的操作,但第一步是根据 ID 进行分组。
var common = productList
.GroupBy(groupId => groupId.Id)
.Select(groupId => groupId.SelectMany(product => product.t)
.GroupBy(groupValue => groupValue.value)
.Where(groupValue => groupValue.Count() > 1)
.Select(values => values.First().value));
关于c# 和 LINQ- 根据对象的 ID 对对象进行分组,然后在其中找到共同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29739120/