简体   繁体   English

C#获取具有共同属性的所有项目

[英]C# Get all items that has a common property

This should be fairly simple, but I'm having a really headache, I think I need some sleep. 这应该很简单,但是我真的很头疼,我想我需要睡觉。

I have a List from some code 我有一些代码的清单

The property object is like : 该属性对象类似于:

public class Properties {
    public int IdProperty 
    public int ProductId
}

This is much as a KeyValue pair. 这与KeyValue对非常相似。 With example this values: 通过示例,该值是:

Product - Property
1          1
1          2
2          1
2          3
3          1
3          3

What I want is to get, from that list, the properties that has all products (in this case, properties with id 1) 我想要从该列表中获得具有所有产品的属性(在这种情况下,是ID为1的属性)

the return list should be: 退货清单应为:

1           1
2           1
3           1

this should be really simple, isnt it ? 这应该很简单,不是吗? (trying it using lambda linq) (使用lambda linq尝试)

Added tryed queries: 添加了尝试查询:

properties.Where(p => properties.All(x => x.IdProperty == p.IdProperty));
properties.Join(properties, p=>p.IdProperty, ... not sure what to put on other params);

some crazy 2 way lists to match. 一些疯狂的2种方式来匹配。

note: I don't know the common property. 注意:我不知道共同财产。

return properties.Where(p => p.PropertyId == 1);

Where properties is an IEnumerable<Properties> containing the property objects you want to select from. 其中propertiesIEnumerable<Properties>其中包含要从中选择的属性对象。

EDIT Now understanding your question, one way to get all property ids common to all products would be: 编辑现在了解您的问题,获取所有产品共有的所有属性ID的一种方法是:

var productCount = properties.Select(p => p.ProductId).Distinct().Count();
return properties.Where(p => properties.Count(x => x.IdProperty == p.IdProperty) == productCount);

I guess you don't know which property is common to all products... 我想您不知道所有产品共有哪个属性...

// get number of products
var nbOfProducts = properties.Select(x => x.Product).Distinct().Count();

// group records by property
// and get only groups with number of items same as number of products
var result = properties.GroupBy(x => x.Property)
                       .Where(g => g.Count() == nbOfProducts)
                       .SelectMany(g => g);
yourCollection.Where(p => p.PropertyId == 1);

or 要么

yourCollection.GroupBy(p => p.PropertyId);

This 2nd option will group them so that you can get other ones if you need them. 此第二个选项会将它们分组,以便您在需要时可以获取其他选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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