2014-05-21 90 views
0

這應該是相當簡單的所有項目,但我有一個很頭疼,我想我需要一些睡眠。C#獲取具有共同財產

我有一個列表從一些代碼

屬性對象是這樣的:

public class Properties { 
    public int IdProperty 
    public int ProductId 
} 

這是多達密鑰值對。隨着例如該值:

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

我想要的是得到的,從該列表中,具有所有產品的性能(在這種情況下,ID爲1的屬性)

返回列表應該是:

1   1 
2   1 
3   1 

這應該是很簡單的,是不是? (使用lambda LINQ嘗試它)

新增tryed查詢:

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

一些瘋狂的2路列表相匹配。

注:我不知道的共同財產。

+1

你應該表現出你已經嘗試查詢。添加了 – MarcinJuraszek

+0

。他們不工作,所以我認爲沒有任何價值,但要證明我至少嘗試了一些東西。在我看來,這是沒有得到的。 –

回答

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

哪裏properties是包含要從選擇屬性對象的IEnumerable<Properties>

編輯 現在理解你的問題,把所有財產的一種方式IDS共同所有的產品將是:

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

我不知道共同財產。 –

+0

我不認爲他知道所有人都會遇到的財產;) – MarcinJuraszek

+1

對,我誤解了這個問題。讓我調整它。 –

-1
yourCollection.Where(p => p.PropertyId == 1); 

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

這第二個選項將組他們讓你可以得到其他的,如果你需要他們。

+0

我不知道共同財產。 –

3

我猜你不知道哪個屬性是通用於所有產品...

// 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);