Home > OS >  how to select values from list having the order with last occurrence in c#
how to select values from list having the order with last occurrence in c#

Time:06-13

enter image description here

the expected result is new list with last occurrence order. Is it possible using the group by. Please do helpful

CodePudding user response:

var list = new List<string> {"name1", "name2", "name1", "name3", "name4", "name2", "name3"};
var result = list
               .Select((value, index) => (value, index))
               .GroupBy(x => x.value)
               .Select(g => g.Last());

CodePudding user response:

Obj obj0 = new() { Id = 0, Name = "name1" };
Obj obj1 = new() { Id = 1, Name = "name2" };
Obj obj2 = new() { Id = 2, Name = "name1" };
Obj obj3 = new() { Id = 3, Name = "name3" };
Obj obj4 = new() { Id = 4, Name = "name4" };
Obj obj5 = new() { Id = 5, Name = "name2" };
Obj obj6 = new() { Id = 6, Name = "name3" };

List<Obj> list = new() { obj0,obj1,obj2, obj3 , obj4 , obj5 , obj6};

var result = list.OrderByDescending(o => o.Id).DistinctBy(p => p.Name).OrderBy(o => o.Id);

foreach (Obj obj in result)
{
    Console.WriteLine(obj);
}
record Obj
{
    public int Id { get; set; }
    public string Name { get; set; }
}
  •  Tags:  
  • c#
  • Related