0

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:

Example

Does anyone got an Idea or an tip how to achieve this?

  • What happens if two objects have the same `Teil` property value but different `Preis` and `ExtraInfo` property values? Which one remains? – gunr2171 Jan 18 '23 at 12:59
  • If Teil is an duplicate, then Preis and ExtraInfo could be different but if Teil is dusplicate It should remove the full row – NadiaBallshek Jan 18 '23 at 13:00
  • That doesn't answer my question. Please [edit] your post with an example input list and the expected output. If you've attempted something, please include that with the actual behavior. – gunr2171 Jan 18 '23 at 13:01
  • thats not Import which remains, importend is that Teil got no duplicates – NadiaBallshek Jan 18 '23 at 13:02
  • Related: [LINQ's Distinct() on a particular property](https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property). – Theodor Zoulias Jan 18 '23 at 13:05
  • The first duplicate value that is found should get removed – NadiaBallshek Jan 18 '23 at 13:05
  • If you're using .NET6 or higher, you can use the [`DistinctBy`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinctby?view=net-7.0) linq method: `var distinctList = list.DistinctBy(x => x.Teil);` – ambroise.la Jan 18 '23 at 13:07
  • @ambroise.la the problem with that is it's dependent on the ordering of your list for which object remains when the non-selected properties are different. – gunr2171 Jan 18 '23 at 13:09
  • @gunr2171 You're right but in that particular case I don't think it's an issue (comment from author: "thats not Import which remains, importend is that Teil got no duplicates"). – ambroise.la Jan 18 '23 at 13:11

1 Answers1

1

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
AoooR
  • 370
  • 1
  • 9