简体   繁体   English

使用C#比较后从list <>添加列表项

[英]Adding list item from list<> after comparing using c#

I do have List control, in which I am adding items. 我确实有List控件,正在其中添加项目。 I have another generic list of say List for comparing, I want to compare the items of List control, and if I found the match I don't wants to include it in my another list say list. 我还有另一个要比较的“说”列表的通用列表,我想比较“列表”控件的项目,如果找到匹配项,则不想将其包括在另一个“说”列表中。

foreach( S s1 in S_list)
{
    if (ex.Count > 0)  // If list not empmty
    {
        foreach(Ex li in ex)  // 
        {
            if (s1.Name.Equals(li.ToString()))
            {
                flag=true;
                ex.Add(s1.Name);
            }
        }
    }
    else
    {
        ex.Add(s1.Name);
    }
}

Problem is: 问题是:

Its causing duplication in my ex list, how to get it done? 它在我的前列表中引起重复,如何完成?

I'm not sure that I understood what are you trying to achieve, but this code looks suspicious to me: 我不确定我是否理解您要实现的目标,但是这段代码对我来说可疑:

foreach(Ex li in ex)  // 
{
    if (s1.Name.Equals(li.ToString()))
    {
        flag=true;
        ex.Add(s1.Name);
    }
}

So, you add s1.Name to list every time when you find the same element in the list? 因此, s1.Name在列表中找到相同元素时,都将s1.Name添加到列表中? This way ex will be populated with elements equal to the first added element. 这样,将用等于第一个添加元素的元素填充ex

Possibly something like this will do the job: 可能是这样的:

foreach( S s1 in S_list)
{
    boolean foundInEx = false;
    foreach(Ex li in ex)  // 
    {
        if (s1.Name.Equals(li.ToString()))
        {
            foundInEx = true;
            break;
        }
    }
    if(!foundInEx) 
    {
        ex.Add(s1.Name); //only executed when there is no such element in ex
    }
}

Shorter way using LINQ Count : 使用LINQ Count的更短方法:

foreach( S s1 in S_list)
{
    if(ex.Count(li => s1.Name.Equals(li.ToString()))>0) 
    {
        ex.Add(s1.Name); //only executed when there is no such element in ex
    }
}

Also you can use LINQ Distinct if you want to get unique elements from list: 如果要从列表中获取唯一元素,也可以使用LINQ Distinct

var uniqueNames = S_list.Select(x => x.Name).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM