2014-09-30 60 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