Checking for duplicates in a List of Objects C#

后端 未结 7 742
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 20:35

I am looking for a really fast way to check for duplicates in a list of objects.

I was thinking of simply looping through the list and doing a manual comparison th

7条回答
  •  臣服心动
    2020-12-29 21:13

    I like using this for knowing when there are any duplicates at all. Lets say you had a string and wanted to know if there was any duplicate letters. This is what I use.

    string text = "this is some text";
    
    var hasDupes = text.GroupBy(x => x).Any(grp => grp.Count() > 1);
    

    If you wanted to know how many duplicates there are no matter what the duplicates are, use this.

    var totalDupeItems = text.GroupBy(x => x).Count(grp =>  grp.Count() > 1);
    

    So for example, "this is some text" has this...

    total of letter t: 3

    total of letter i: 2

    total of letter s: 3

    total of letter e: 2

    So variable totalDupeItems would equal 4. There are 4 different kinds of duplicates.

    If you wanted to get the total amount of dupe items no matter what the dupes are, then use this.

    var totalDupes = letters.GroupBy(x => x).Where(grp => grp.Count() > 1).Sum(grp => grp.Count());
    

    So the variable totalDupes would be 10. This is the total duplicate items of each dupe type added together.

提交回复
热议问题