简体   繁体   中英

Adding list item from list<> after comparing using c#

I do have List control, in which I am adding items. 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? This way ex will be populated with elements equal to the first added element.

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 :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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