Home > database >  Way to DistinctBy will remove duplicates from a repeating id but if the value is null will leave the
Way to DistinctBy will remove duplicates from a repeating id but if the value is null will leave the

Time:06-14

There is a way to prevent duplicates Id, but if id is null to let the list to be with duplicates null?

data = data
  .OrderByDescending(x => x.DocVersionNumber)
  .DistinctBy(x => x.RequireId)
  .ToList();

in this way if I have few items with null on RequireId, only one will stay.

Thanks

CodePudding user response:

you can do it like this

var temp = data.Where(x => x.RequireId == null).ToList();
data = data.Where(x => x.RequireId != null)
  .OrderByDescending(x => x.DocVersionNumber)
  .DistinctBy(x => x.RequireId)
  .ToList();
data.AddRange(temp);

CodePudding user response:

data = data
  .Where(i => i.RequireId != null)
  .OrderByDescending(x => x.DocVersionNumber)
  .DistinctBy(x => x.RequireId)
  .ToList();
  • Related