2014-09-30 59 views
0

我有代碼的列表如下C#的LINQ所有條件

public Code{ 
    int id; 
    string Description; 
} 

List<Code> AllCodes; 

我有從不同的源中選擇的代碼的列表。

​​

使用linq,我需要加入AllCodesrelatedCodes,這樣的結果列表中包含所有給定id S的Code元素。衆所周知,relatedCodes中的所有int值在AllCodes中都是有效的id s。 [relatedCodesint陣列]

result = //how to write the linq expression? 

我是想這樣的事情,但它拋出錯誤

result = AllCodes.All(x => x.Code==relatedCodes); 
+4

東西哪裏,並可包含。你有什麼嘗試? – CodeCaster 2014-09-30 06:47:14

+2

這不應該太難,請您提供迄今爲止嘗試過的代碼示例嗎? – Maritim 2014-09-30 06:47:49

回答

2

所有的首先是無關Join。問題簡要地爲How can I get the Codes of which relatedCodes contains the id?。您可以使用Where來過濾您的列表。

var result = AllCodes.Where(c=> relatedCodes.Contains(c.id)); 
2
List<Code> result = AllCodes.Where(x => relatedCodes.Contains(x.id)).ToList(); 
2

編輯: 由於relatedCodesint[]類型(我使用Code類型的數組)的溶液看起來略有不同,但不太多的:

var relatedCodes = new int[2] { 2, 4 }; 

var joinedCodes = from ac in AllCodes 
        join rc in relatedCodes on ac.Id equals rc 
        select ac; 

ORIGINAL答案

一種可能性是使用連接:

void Main() 
{ 
    var AllCodes = new List<Code>() 
    { 
     new Code() {Id = 1, Description="Foo1"}, 
     new Code() {Id = 2, Description="Bar2"}, 
     new Code() {Id = 3, Description="Foo3"}, 
     new Code() {Id = 4, Description="Bar4"} 
    }; 

    var relatedCodes = new Code[2] 
    { 
     new Code() {Id = 2, Description="Bar2"}, 
     new Code() {Id = 4, Description="Bar4"} 
    }; 

    var joinedCodes = from ac in AllCodes 
         join rc in relatedCodes on ac.Id equals rc.Id 
         select ac; 
    joinedCodes.Dump(); 
} 

// Define other methods and classes here 
public class Code{ 
    public int Id { get; set; } 
    public string Description { get; set; } 
} 

輸出繼電器:

enter image description here