0

I have a list where I'm applying the following condition with linQ:

I want to select all items where Name contains a certain string.

var nameFilter = result
                     .Where(e => e.Name.Contains(requestedValue))
                     .ToList();

At the end, sometimes it happens that I am having a list with repeated names:

For example:

requestedValue = 'form';

I end up with:

Name           Price
transformer    100
transformer    20 
formation      340
former         201

I got transformer twice. In that case, I want to only leave transformer with the least price : 20

How could I do this with linQ without looping?

maccettura
  • 10,514
  • 3
  • 28
  • 35
HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89

1 Answers1

2

You can take advantage of GroupBy method

 var nameFilter = result.Where(e => e.Name.Contains(requestedValue))
    .GroupBy(k=>k.Name, g=>g.Price, (k,g)=>new Model {Name = k, Price = g.Min()})
    .ToList();

where new Model should be changed to your class name.

If you have more properties to return probably it will be more convenient to do

 var nameFilter = result.Where(e => e.Name.Contains(requestedValue))
            .GroupBy(k => k.Name, g => g, (k, g) =>
            {
                var minPrice = g.Min(x => x.Price);
                return g.First(x => x.Price == minPrice);
            }).ToList();

Finding minPrice and finding the item with minPrice can be done is a single for loop or, for example, by using following discussion here

Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80