Thomas
Thomas

Reputation: 1319

How to check if a list of object contains an object with a specified properties

I have a list of duplicates object:

var duplicates = workspace.Maps.GroupBy(m => m.sFolder).SelectMany(grp => grp.Skip(1)).ToList();

I want an if statement to check if the list contains an object with a particular properties:

if (duplicates.Contains(myObject.sFolder)) // "myObject.sFolder" raise an error (of course)
{
    // Do stuff
}

Is there a simple way to do it?

Upvotes: 1

Views: 136

Answers (4)

Arash
Arash

Reputation: 885

You can use foreach

  foreach (var item in duplicates)
            {
                if (item.sFolder == myObject.sFolder )
                {
                    // Do stuff
                    break;
                }
            }

Upvotes: 0

Oliver
Oliver

Reputation: 45071

Just in case you need the duplicate object for further inspection try

var duplicate = duplicates.FirstOrDefault(m => m.sFolder == myObject.sFolder);

if(duplicate != null)
{
    // Further check duplicate
}

Upvotes: 1

Monolithcode
Monolithcode

Reputation: 618

Not sure on whats being compared here but something like this?

if (duplicates.Any(x => x.sFolder == myObject.sFolder)) 
{
    // Do stuff
}

Upvotes: 1

Mostafiz
Mostafiz

Reputation: 7352

You can check by this way

if (duplicates.Any(a => a.sFolder == myObject.sFolder))
{
    // Do stuff
}

Upvotes: 5

Related Questions