linq to xml - display results based on array or list
I have a xml file on w开发者_如何学编程hich I want to make a query to display all articles with certain Id's in it.This is what I tried but somehow I can't get it to work. I looked around and all I could find were examples using linq to sql.
Any help would be appreciated...
Cheers, Terry
The id's are stored like this in the xml
<relatedcontent articleID="1, 2, 3, 4" />
Here's my linq
var mylinks = (from item in relatedLinks.Descendants("link")
where item.Attribute("linkID").Value.Contains("1, 2")
select new
{
testlink = item.Value
});
foreach (var newarticles in mylinks)
{
Response.Write(newarticles .testlink);
}
What you are doing now is to look for articles where the Id contains the string "1, 2", like if the Id was "5, 8, 1, 2, 9".
What you want is probably the opposite; to find the articles where "1, 2" contains the Id, i.e. the articles with Id "1" and "2":
var ids = new HashSet<string>();
ids.Add("1");
ids.Add("2");
var mylinks =
from item in relatedLinks.Descendants("link")
where ids.Contains(item.Attribute("linkID").Value)
select new { testlink = item.Value };
精彩评论