简体   繁体   中英

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

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM