查找重复的项目数在C#列表 [英] Find the count of duplicate items in a C# List

查看:178
本文介绍了查找重复的项目数在C#列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#列表。代码如下所述:

I am using List in C#. Code is as mentioned below:

TestCase.cs

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;
    }
}



我createing名单是:

List I am createing 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;
    }

现在,我通过列表进行迭代。我想找到多少重复的测试用例与同ScenarioID名单在那里。有没有什么办法使用LINQ或List中的任何内置的方法来解决?

Now I am iterating through the list. I want to find the how many duplicate testcases are there in a list with same ScenarioID. Is there any way to solve it using Linq or any inbuilt method for List?

问候,
Priyank

Regards, Priyank

推荐答案

试试这个:

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

这篇关于查找重复的项目数在C#列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆