kittyhawk
kittyhawk

Reputation: 698

LINQ Returns Conditional Object

I have a simple LINQ statement that returns a list of objects based on querying an Xml file.

        var locations = from s in xdoc.Descendants("RECORD")
                        where IdList.Contains(s.Element("ID1").Value)
                        select new Location
                                   {
                                       Id = s.Element("ID1").Value
                                   }; 

Each Xml record also has an ID2 element that I want to return if "Contains" is true. So basically, I want my Location object to be conditional based on what the IdList Contains returns (it could be ID1 or ID2). Something like:

if(IdList.Contains(s.element("ID1").value){ select new Location {Id = s.Element("ID1").Value};}
if(IdList.Contains(s.element("ID2").value){ select new Location {Id = s.Element("ID2").Value};}

Can this be done in a single LINQ statement?

Upvotes: 2

Views: 588

Answers (3)

anonymousen
anonymousen

Reputation: 96

Try this:

var locations = from s in xdoc.Descendants("RECORD")
                from x in IdList
                where s.Element("ID1").Value == x || s.Element("ID2").Value == x
                select new Location { Id = x };

This should work as long as for each element in xdoc.Descendants("RECORD"), IdList contains either s.Element("ID1").Value or s.Element("ID2").Value but not both (otherwise you will get two Location objects for that particular record).

Upvotes: 0

Aducci
Aducci

Reputation: 26694

var locations = from s in xdoc.Descendants("RECORD")
                        select new Location
                                   {
                                       Id = IdList.Contains(s.Element("ID1").Value) ? 
                                       s.Element("ID1").Value : 
                                         (IdList.Contains(s.Element("ID2").Value) ? 
                                          s.Element("ID2").Value : 
                                          DefaultValue)
                                   }; 

If you need the location to contain either ID1 or ID2 just add a where condition

Upvotes: 4

Priyank
Priyank

Reputation: 10623

Refer this: If Else in LINQ

Upvotes: 0

Related Questions