Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple column and distinct one column by LINQ?

Tags:

c#

I have:

var names = db.tblPosts.Select(x => new { x.UserID, x.title }).Distinct().ToList();

I want select UserID and title and UserID is distinct.

but not worked and userID is not distinct..

like image 941
Samiey Mehdi Avatar asked Sep 21 '25 07:09

Samiey Mehdi


1 Answers

var items = db.tblPosts
              .GroupBy(x => x.UserId)
              .Select(g => new { UserId = g.Key, Title = g.FirstOrDefault().Title })
              .ToList();

It will return first Title for each UserId. Add additional OrderBy/ThenBy to sort items within group before taking first one.

like image 195
MarcinJuraszek Avatar answered Sep 22 '25 20:09

MarcinJuraszek