Search code examples
c#linqlinq-to-sqllinq-to-entitieslinq-to-objects

linq query to filter textvalue pair and remove duplicates by value


I'm trying to filter the results I'm getting by removing some of the items I have in my custom dictionary by their value. So if there are multiple items with the same value I would like to have only one sample of that pair.

This is the custom class I have where I'm storing the values:

                public class ValuePair
                {
                    public string Text { get; set; }
                    public string Value { get; set; }
                }

Here is how I'm retrieving the values:

   List<ValuePair> items = GetResults(db)             
               .AsEnumerable()
               .Distinct()
               .Select(v => new TextValuePair
               {
                   Text = ToTitleCase(v.NameOfTown),
                   Value = v.NameOfTown
               })              
               .ToList();

I would like to know how I can refresh the results and get only one sample of the items filtered by the value, not by the key.

How can I do that?


Solution

  • You can group by Value then take the first item of the grouped items.

    List<ValuePair> items = GetResults(db)             
               .AsEnumerable()
               .Distinct()
               .Select(v => new TextValuePair
               {
                   Text = ToTitleCase(v.NameOfTown),
                   Value = v.NameOfTown
               })
               .GroupBy(x => x.Value)
               .Where(x => x.Key == "filter") // filter by Value (the prop name is Key)
               .Select(x => x.First()) 
               .ToList();