开发者

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?


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


Refer this: If Else in LINQ


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜