Search code examples
c#linqlambda

Why am I getting an ambiguous invocation error in Where?


I have a simple object that I'm creating a collection of. From that collection I need to find duplicates that have the same TransitMapSegmentID.

public class LineString
{
    public int TransitLineID { get; set; }
    public string TransitLineName { get; set; }
    public int TransitMapSegmentID { get; set; }
    public string HexColor { get; set; }
    public double[][] Coordinates { get; set; }
}

var lineStrings = new List<LineString>();

With the code below I'm getting a "ambiguous invocation match" error from he lambda expression below. Can anyone explain why?

var result = lineStrings
             .Where(a => lineStrings
             .Count(b => b.TransitMapSegmentID == a.TransitMapSegmentID) > 1);

Solution

  • If you want to find all duplicate lines based on their TransitMapSegmentID, use Enumerable.GroupBy:

    var result = lineStrings
                .GroupBy(ls => ls.TransitMapSegmentID)
                .Where(grp => grp.Count() > 1)
                .SelectMany(grp => grp);