Nick LaMarca
Nick LaMarca

Reputation: 8188

Filter Collections From A Property With Collections Linq

I have an object Called MyConnection with a property of Sources which is of type List I am having trouble writing linq code to find all the MyConnections in a List where a connection has a Source of "".

I tried this but it doesnt seem to run..

MyConnection initialActivity = currentActivities.ToList().Where(x => x.Sources.Contains(String.Empty));

Upvotes: 0

Views: 71

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460228

Where returns an IEnumerable<MyConnection> not a single MyConnection. So you could enumerate all in a foreach or take one f.e. with First.

IEnumerable<MyConnection> allWithEmptySource = currentActivities
    .Where(con => con.Sources.Any(s => string.IsNullOrEmpty(s)));
if(allWithEmptySource.Any())
{
    MyConnection first = allWithEmptySource.First();
}

Upvotes: 1

Rawling
Rawling

Reputation: 50144

If you're only trying to get one activity that has a Source of "", rather than all of them, use

MyConnection initialActivity = currentActivities.ToList()
    .FirstOrDefault(x => x.Sources.Contains(String.Empty));

which will give you null if there are no such activities, andj ust the first if there are one or more.

Alternatively to FirstOrDefault, use:

  • First to give you the first but throw an exception if there are none
  • Single to give you a single match and throw an exception of there are 0 or >1 matches
  • SingleOrDefault to give you a single match or no match, andthrow and exception if there are >1 matches.

If you want all of them, you return type will be an IEnumerable<MyConnection>, not a single one:

IEnumerable<MyConnection> initialActivities = = currentActivities.ToList()
    .Where(x => x.Sources.Contains(String.Empty));

You can then foreach over this, or call ToList or ToArray on it to get a list or an array.

N.B. You probably don't need to be calling .ToList() in the middle of your line here.

Upvotes: 0

SLaks
SLaks

Reputation: 887807

.Where() returns a sequence of matching elements.

You can't assign that to a variable of type MyConnection.

Instead, you can call methods like .Last() to get a single element.

Upvotes: 0

Related Questions