Search code examples
c#linq

Convert foreach to LINQ for practice and learning purposes


I wrote this code. It works. It is easy to read and easy to debug. However for learning purposes for a few hours today I tried to convert it to some sort of LINQ with JOIN or GroupJoin or something like that. Because if you look at the WHERE clause my gut is telling me I could do that with some sort of JOIN maybe and get rid of foreach but well I could not come up with that syntax.

So I wanted to see if you can help me re-write it that way?

foreach (var f in myData)
{
    var res = new FinalClass
    {
        ID = f.ID,
        Floor = f.Floor,
        Description = f.Description
    };

    var setOne = setOneDataList.Where(b => b.FieldID == f.ID).Select(t => new CommonClass
    {
        FieldName = t.Field,
        Color = t.Color,
        Status = t.Status
    }).OrderBy(b => b.FieldName);

    var setTwo = setTwoDataList.Where(f => f.FieldID == f.ID).Select(t => new CommonClass
    {
        FieldName = t.Field,
        Color = t.Color,
        Status = t.Status
    }).OrderBy(b => b.FieldName);


    res.SetOne = setOne;
    res.SetTwo = setTwo;   

    result.Add(fs);
}

Solution

  • I took to long and I see someone already pasted the answer :)

    But I'll submit mine, since I suggest using "one . per line" approach to writing LINQ. Don't you think it's more readable this way?

    myData.Select(f => new FinalClass
    {
        ID = f.ID,
        Floor = f.Floor,
        Description = f.Description,
        SetOne = setOneDataList
            .Where(b => b.FieldID == f.ID)
            .Select(t => new CommonClass
            {
                FieldName = t.Field,
                Color = t.Color,
                Status = t.Status
            })
            .OrderBy(b => b.FieldName),
        SetTwo = setTwoDataList
            .Where(f => f.FieldID == f.ID)
            .Select(t => new CommonClass
            {
                FieldName = t.Field,
                Color = t.Color,
                Status = t.Status
            })
            .OrderBy(b => b.FieldName),
    };