Jacob Turpin
Jacob Turpin

Reputation: 190

LINQ Query for a Nested Class

As a newbie with C# and LINQ, I'm rather confused with the implementation of a particular query I'm attempting. I have an array of one particular class called Session. One of the properties of this class is an array of ActiveConnection, another class. Each ActiveConnection contains an enumeration for ProcessType.

Here's the goal: I need to determine which Session objects from said array contain an ActiveConnection with ProccessType.Guest. After plenty of fiddling, I've got my code below (which doesn't even compile anymore).

// Creating my array Session[]
var sessions = GetSessions();

var busySessions = from sessions
                   where sessions.ActiveConnections.ProcessType != ProcessType.Guest
                   select sessions;

// Do other stuff with this array of busy sessions

Clearly, I don't understand how to implement a LINQ query. Any help would be greatly appreciated.

Upvotes: 1

Views: 1720

Answers (3)

Bryan Watts
Bryan Watts

Reputation: 45445

You need to declare a variable in the from clause, to represent each item in the source:

from session in GetSessions()

Then, you execute a subquery on the entire set of active connections:

where session
    .ActiveConnections
    .Any(connection => connection.ProcessType != ProcessType.Guest)

Finally, you select the sessions that meet the criteria:

select session

Full query:

from session in GetSessions()
where session
    .ActiveConnections
    .Any(connection => connection.ProcessType != ProcessType.Guest)
select session

Upvotes: 1

Ryan Nigro
Ryan Nigro

Reputation: 4619

You can do:

var busySessions = sessions.ToList().Where(s => s.ActiveConnections.Any(ac => ac.ProcessType != ProcessType.Guest)).Select();

OR

var busySessions = (from s in sessions
                   where s.ActiveConnections.Any(ac => ac.ProcessType != ProcessType.Guest)
                   select sessions).ToList();

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61339

You need a nested query for this (since ActiveConnections is a collection):

var result = sessions.Where(session => session.ActiveConnections.Any(conn => conn.ProcessType == ProcessType.Guest));

This will return all sessions where Guest is in the ActiveConnections list (which is what you said). To do what your code did, you would need:

var result = sessions.Where(session => session.ActiveConnections.All(conn => conn.ProcessType != ProcessType.Guest));

Upvotes: 4

Related Questions