-2

Given this class:

public class Tool
    {
        public int Id { get; set; }
        public int Number { get; set; }
        public string Source { get; set; }
    }

And a list of Tools like this:

var tools = new List<Tool>()
            {
                new Tool {Id=444, Number=121, Source="Master"},
                new Tool {Id=777, Number=121, Source="M1"},
                new Tool {Id=333, Number=51, Source="Master"},
                new Tool {Id=555, Number=61, Source="Master"},
                new Tool {Id=848, Number=51, Source="M1"}
                //Many more
            };

How could I use Linq to get a list of distinct Tools by Number and if 2 tools have the same Number select the one whose source is "M1", i.e.the resulting list would contain:

Tool {Id=777, Number=121, Source="M1"}
Tool {Id=848, Number=51, Source="M1"}
Tool {Id=555, Number=61, Source="Master"}
jweaver
  • 661
  • 5
  • 15

3 Answers3

2

Try grouping by Number and get the first element of that,

List<Tool> distinctTool = tools.GroupBy(p => p.Number)
                               .Select(f => f.OrderByDescending(q => q.Source == "M1").First())
                               .ToList();

WORKING FIDDLE

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2

You need to group your Tools by Number and get the First() of them

List<Tool> distinctTool = tools
  .GroupBy(p => p.Number)
  .Select(g => g.OrderByDescending(q => q.Source == "M1").First())      
  .ToList();
Ehsan Ullah Nazir
  • 1,827
  • 1
  • 14
  • 20
2
List<Tool> distinctTool = tools
  .GroupBy(p => p.Number)
  .Select(g => g.OrderByDescending(q => q.Source == "M1").First())
  .ToList();
koryakinp
  • 3,989
  • 6
  • 26
  • 56