C#Linq所有条件

时间:2014-09-30 06:45:08

标签: c# linq

我有一个代码列表如下

public Code{
    int id;
    string Description;
}

List<Code> AllCodes;

我有一个来自不同来源的选定代码列表。

var relatedCodes = //gets the list of int 'id's from a different source.

使用linq,我需要加入AllCodesrelatedCodes,以便结果列表包含给定Code的所有id个元素。众所周知,int中的所有relatedCodes值都在id中有效AllCodes s。 [relatedCodesint数组]

result = //how to write the linq expression?

我正在尝试这样的事情,但它会抛出错误

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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 :(得分:2)

修改 由于relatedCodes的类型为int[](我使用了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;

原始回答

一种可能性是使用join:

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