简体   繁体   中英

I cant get ordered by id items when using distinct

I'm braking my head over this and tried a lot of version but it's just not working for me I need to get a distinct ordered by id. I understand that after distinct I need to order my list, but i can't get any identifier. And the results I'm getting has no logical order (1,2, 8, 4, 5,6,9). Please advise me .

public class TakeAway
{
    public int TakeAwayId { get; set; }
    public int GenreId { get; set; }
    public virtual Genre genre { get; set; }
}

public class Genre
{
    public int GenreId { get; set; }
    public string GenreName { get; set; }
    public List<TakeAway> TakeAwys { get; set; }

}

var allDishGenre = 
    db.TaKeAways.Select(x => x.genre.GenreName).Distinct().OrderBy(g => g).ToList();
ViewBag.GenreTab = allDishGenre;

This:

db.TaKeAways.Select(x => x.genre.GenreName).Distinct()

returns a distinct list of names (Strings), which do not have any identifiers. You need:

db.TakeAways
  .GroupBy(ta => ta.genre.GenreName)
  .Select(g => g.FirstOrDefault())
  .OrderBy(ta => ta.TakeAwayId)
  .ToList()

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