LINQ匹配select语句中的两个列表

时间:2016-04-20 07:40:17

标签: c# linq lambda

我有一堆通用类,看起来像这样:

public class MyList<T0, T1, T2>
{
    public T0 Column0;
    public T1 Column1;
    public T2 Column2;
}

...我在两个列表TempResults (Column0-Column15)Disagio (Column0-Column3)中使用它们。现在我想创建一个新列表,其中包含来自TempResults的3列和来自Disagio的3列,我需要将Disagio.Column1TempResults.Column13匹配,然后返回Disagio.Column2(总是会有0或0或1场比赛)。整个代码:

EndResults = TempResults
    .Select(sel => new MyList<string, string, string, string>
    {
        Column0 = sel.Column0,
        Column1 = //ugly part goes here, see below
        Column2 = sel.Column1,
        Column3 = sel.Column12
    })
    .DistinctBy(x => x.Column0)
    .ToList();

到目前为止我已尝试过:

//Returns an empty list
Disagio.Where(x => x.Column1 == sel.Column13).First().Column2.ToString()


//It returns something, but I doubt it's correct
Disagio.Join(TempResults, x => x.Column1, y => y.Column13, (a, b) => a).First().Column2.ToString()

我可以通过循环解决问题,但我真的不想。这些列表永远不会过长,在这种情况下,内存和速度不如可读性重要。

1 个答案:

答案 0 :(得分:2)

试试这个:

    EndResults =
    (
        from tr in TempResults
        join d in Disagio on tr.Column13 equals d.Column1
        select new MyList<string, string, string, string>()
        {
                Column0 = tr.Column0,
                Column1 = d.Column2,
                Column2 = tr.Column1,
                Column3 = tr.Column12
        }
    )
        .DistinctBy(x => x.Column0)
        .ToList();