I got an List which got Data from an class, that has this propertys:
public string ExtraInfo { get; set; }
public string Teil { get; set; }
public decimal Preis { get; set; }
after I added Data to this list I have the Problem that in Column "Teil" a lot of duplicates are.
I want to remove every duplicate from "Teil" and when its removing it should remove the whole row with "Preis" and "ExtraInfo" from this row.
Normally I would think of distinct but that seems just to delete If the full row has an duplicate.
List example:
Does anyone got an Idea or an tip how to achieve this?
You can use DistinctBy
method of type List
. (Check Documentation). It will apply Distinct
method only based on Teil
attribute.
List<Data> examples = new()
{
new Data { ExtraInfo = "InfoA", Teil = "TeilA", Preis = 0 },
new Data { ExtraInfo = "InfoA", Teil = "TeilA", Preis = 0 },
new Data { ExtraInfo = "InfoA", Teil = "TeilB", Preis = 0 },
new Data { ExtraInfo = "InfoA", Teil = "TeilA", Preis = 0 },
};
var result = examples.DistinctBy(data => data.Teil).ToList();
result.ForEach(res => Console.WriteLine($"ExtraInfo: {res.ExtraInfo}, Teil: {res.Teil}, Preis: {res.Preis}"));
// Output result :
// ExtraInfo: InfoA, Teil: TeilA, Preis: 0
// ExtraInfo: InfoA, Teil: TeilB, Preis: 0