CookedCthulhu
CookedCthulhu

Reputation: 787

LINQ match two lists within a select statement

I have a bunch of generic classes which all look like this:

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

... and I'm using them in two lists, TempResults (Column0-Column15) and Disagio (Column0-Column3). Now I want to create a new list that contains 3 columns from TempResults and one from Disagio, where I need to match Disagio.Column1 with TempResults.Column13 and then return Disagio.Column2 (there will always bei either 0 or 1 matches). The whole code:

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

What I've tried so far:

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

I could solve the problem with a loop but I really don't want to. The lists wil never be overly long, memory and speed are less important than readability in this case.

Upvotes: 0

Views: 68

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

Try this:

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

Upvotes: 2

Related Questions