Home > Software engineering >  LINQ filter list based on given conditions
LINQ filter list based on given conditions

Time:10-08

I'm currently working on a .NET application. I need to write a LINQ query to filter a List<SearchResult> given in the example below.

Allowed are the combinations of CompanyId ContactId or CompanyId (without ContactId) as a key for the result, the entries in the result list must be distinct.

The key in the result list is a combination of unique "CompanyID ContactId" OR unique "CompanyID". As an example, in the result list as a key I can have one "companyID 1", and several "companyID 1" ContactID (1, 2, 3, ...) BUT eacht ContactID only one time in combination with one CompanyID i.e. {1},{1, 1}, {1, 2}, {1, 3} but not a second time {1, 1} or {1}.

public class SearchResult
{
    public int? CompanyId {get; set;}
    public int? ContactId {get; set;}
}

public class Program
{
    public static void Main()
    {
        var searchResults = new List<SearchResult>
        {
            new SearchResult { CompanyId = 1, ContactId = 1 }, // yes
            new SearchResult { CompanyId = 2, ContactId = 3 }, // yes
            new SearchResult { CompanyId = 2, ContactId = 4 }, // yes
            new SearchResult { CompanyId = 1 }, // yes
            new SearchResult { CompanyId = 2 }, // yes
            new SearchResult { CompanyId = 1, ContactId = 1 }, // no
            new SearchResult { CompanyId = 1 }, // no
            new SearchResult { }, // no
            new SearchResult { CompanyId = null }, // no
            new SearchResult { CompanyId = null, ContactId = null }, // no
            new SearchResult { ContactId = null }, // no
        };
        
        // Unfortunately my LINQ query doesn't work correctly 
        var result = searchResults
                      .GroupBy(sr => sr.CompanyId)
                      .Select(grp => grp.First());
        
        foreach(SearchResult sr in result){         
            Console.WriteLine(sr.CompanyId   " "   sr.ContactId);
        }
    }
}

My current LINQ query doesn't work correctly - it's also quite basic. I only get the result: [{1, 1},{2, 3}], it's really tricky.

Though the desired result should be [{1, 1},{2, 3},{2, 4}, {1},{2}].

Do you know how to retrieve the correct result?

CodePudding user response:

Very close, however .GroupBy both CompanyId and ContactId (instead of just CompanyId) & then get the non-dupes using .First().

var result = searchResults
    .GroupBy(sr => new { sr.CompanyId, sr.ContactId })
    .Select(x => x.First());
  • Related