Find the number of duplicate items in a C # list

I am using List in C #. The code is listed below:

TestCase.cs

 public class TestCase
{
    private string scenarioID;
    private string error;

    public string ScenarioID
    {
        get
        {
            return this.scenarioID;
        }
        set
        {
            this.scenarioID = value;
        }
    }

    public string Error
    {
        get
        {
            return this.error;
        }
        set
        {
            this.error = value;
        }
    }

    public TestCase(string arg_scenarioName, string arg_error)
    {
        this.ScenarioID = arg_scenarioName;
        this.Error = arg_error;
    }
}

The list I create is:

private List<TestCase> GetTestCases()
    {
        List<TestCase> scenarios = new List<TestCase>();
        TestCase scenario1 = new TestCase("Scenario1", string.Empty);
        TestCase scenario2 = new TestCase("Scenario2", string.Empty);
        TestCase scenario3 = new TestCase("Scenario1", string.Empty);
        TestCase scenario4 = new TestCase("Scenario4", string.Empty);
        TestCase scenario5 = new TestCase("Scenario1", string.Empty);
        TestCase scenario6 = new TestCase("Scenario6", string.Empty);
        TestCase scenario7 = new TestCase("Scenario7", string.Empty);

        scenarios.Add(scenario1);
        scenarios.Add(scenario2);
        scenarios.Add(scenario3);
        scenarios.Add(scenario4);
        scenarios.Add(scenario5);
        scenarios.Add(scenario6);
        scenarios.Add(scenario7);

        return scenarios;
    }

Now I repeat the list. I want to find how many duplicate checks are on the list with the same ScenarioID. Is there a way to solve this using Linq or any built-in method for List?

Regards, Priyank

+5
source share
6 answers

Try the following:

var numberOfTestcasesWithDuplicates = 
    scenarios.GroupBy(x => x.ScenarioID).Count(x => x.Count() > 1);
+18
source

As a first idea:

int dupes = list.Count() - list.Distinct(aTestCaseComparer).Count();
+8
source
var groups = scenarios.GroupBy(test => test.ScenarioID)
    .Where(group => group.Skip(1).Any());

ScenarioID, . - , - .

, .Skip(1).Any() , .Count() Where , , .

+4

To just get a duplicate counter:

int duplicateCount = scenarios.GroupBy(x => x.ScenarioID)
                              .Sum(g => g.Count()-1);
+4
source

Something like this is possible

var result= GetTestCases()
            .GroupBy (x =>x.ScenarioID)
            .Select (x =>new{x.Key,nbrof=x.Count ()} );
+2
source

To get the total number of duplicates, another one:

var set = new HashSet<string>();
var result = scenarios.Count(x => !set.Add(x.ScenarioID));

To get various duplicates:

var result = scenarios.GroupBy(x => x.ScenarioID).Count(x => x.Skip(1).Any());
+1
source

All Articles