-1

The my object (Photo) have 3 property(ID, Name, Photo)

ID     Name     Photo  
***********************
1      a        1.jpg
2      a        2.jpg
3      b        3.jpg
4      b        4.jpg
5      c        5.jpg
*************************
How can i get first record in groupby(name) by using linq lambda? like below table

ID     Name     Photo  
**********************
1      a        1.jpg
3      b        3.jpg
5      c        5.jpg
***********************

I using this code:

photos.GroupBy(x => x.Name).FirstOrDefault();

But the result just is (name:a) and i need (ID,Name,Photo) values

Aram
  • 63
  • 8

3 Answers3

1
photos.GroupBy(p => p.Name).Select(p => p.First()).ToList();
Aram
  • 63
  • 8
Nazim
  • 639
  • 2
  • 10
  • 26
  • I'd suggest a slightly better version: `photos.GroupBy(p => p.Name).SelectMany(p => p.Take(1)).ToList();`. That approach allows for better refactoring in case a filter is used on the `p` in the `Select`. So something like this: `photos.GroupBy(p => p.Name).SelectMany(p => p.Where(x => x.ID > 3).Take(1)).ToList();` – Enigmativity Apr 02 '20 at 06:27
1

When you do a GroupBy(), the result is an IEnumerable of IGrouping<,>s. In your case, it would be of IGrouping<string, Photo>. So when you try to access the first element you are not getting the first Photo but the first IGrouping, which will have two elements in the example.

The correct way of getting the first Photo of the first group would be something like this:

var firstGroup = photos.GroupBy(x => x.Name).OrderBy(y => y.Key).First(); //or FirstOrDefatult() if you prefer
Photo firstPhotoInGroup = firstGroup.First(); 

Once you get the group you can use it like an IEnumerable with a Key property.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
setemalky
  • 31
  • 5
-1

I'm thinking you possibly may need different than what the accepted answer has - the accepted answer is assuming the list is already sorted in the order it needs to be (by ID) and grabbing the first one. The following solution groups by Name, but then grabs the minimum by ID in that group and reassembles it:

IEnumerable<MetaPhoto> minPhotos = photos
    .GroupBy(photo => photo.Name)
    .SelectMany(photoGroup => photoGroup, (photoGroup, photo) => new { PhotoGroup = photoGroup, Photo = photo })
    .Where(photoGroupPhoto => photoGroupPhoto.Photo.ID == photoGroupPhoto.PhotoGroup.Min(photo => photo.ID))
    .Select(photoGroupPhoto => photoGroupPhoto.Photo);
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87