Search code examples
c#c#-4.0linq-to-objects

Refine LINQ join of two List<T> Objects, Group, and Count


I have two List<T> objects. I want a count of how many items between the two list match. Now I could loop through with a counter as I come across matches....but that would be kinda lame.

However this one is stretching my LINQ knowledge. I believe what I want to do is Join, discern (where), group, and project the count. I came to this approach by reading similar SO questions and LINQ documentation.

However if this is flawed by all means it doesn't have to be this way. I just want the count of matching elements.

So my "master" object is:

public class Master
{
    public StringModel OldText { get; private set; }
    public StringModel NewText { get; private set; }

    public Master()
    {
        OldText = new StringModel();
        NewText = new StringModel();
    }
}

StringModel is:

public class StringModel
{
    public List<strPiece> Lines { get; private set; }

    public StringModel()
    {
        Lines = new List<strPiece>();
    }
}

My LINQ thus far is:

var unchangedJoin = from oldLine in Master.OldText.Lines
                    join newLine in Master.NewText.Lines
                    on oldLine.Type equals newLine.Type
                    where oldLine.Type == "ABC"
                    group oldLine by --as you can see I kinda break down here.

How can I finish this?


Solution

  • Just perform a GroupJoin rather than a Join.

    var unchangedJoin = from oldLine in Master.OldText.Lines
                        join newLine in Master.NewText.Lines
                        on oldLine.Type equals newLine.Type
                        into newMatches
                        where oldLine.Type == "ABC"
                        select oldLine;
    
    var matches = unchangedJoin.Count();