linqtoxml을 사용하여 필터로 고유 한 xlements (속성)를 선택하십시오.

StackOverflow https://stackoverflow.com/questions/345025

  •  19-08-2019
  •  | 
  •  

문제

여기와 유사한 XML 문서가 있습니다.

<items>
 <item cat="1" owner="14">bla</item>
 <item cat="1" owner="9">bla</item>
 <item cat="1" owner="14">bla</item>
 <item cat="2" owner="12">bla</item>
 <item cat="2" owner="12">bla</item>
</items>

이제 LINQ 쿼리를 사용하여 지정된 카테고리에 속하는 모든 고유 한 소유자 (실제로 소유자의 속성 값 만 필요합니다)를 얻고 싶습니다. 내 예에서, Cat 1의 쿼리는 9와 14가 포함 된 목록을 반환 할 것입니다. 어떻게 할 수 있습니까? LINQ 구문은 Lambdas보다 선호됩니다. 미리 감사드립니다;)

도움이 되었습니까?

해결책

조각이 항목 수소에 있다고 가정합니다.

var distinctOwners = (from item in itemsElement.Element("item") 
 where itemElements.Attribute("cat") == 1 
select item.Attribute("owner")).Distinct();

서식 및 계약에 대한 사과!

다른 팁

이 기능을 시도하십시오 :-

static IEnumerable<int> GetOwners(XDocument doc, string cat)
{
    return from item in doc.Descendants("item")
        where item.Attribute("cat").Value == cat
        select (int)item.Attribute("owner")).Distinct();

}
  XElement ele = XElement.Parse(@"<items><item cat=""1"" owner=""14"">bla</item><item cat=""1"" owner=""9"">bla</item>" +
                                @"<item cat=""1"" owner=""14"">bla</item><item cat=""2"" owner=""12"">bla</item>" +
                                @"<item cat=""2"" owner=""12"">bla</item></items>");

  int cat = 1;


  List<int> owners = ele.Elements("item")
    .Where(x=>x.Attribute("cat").Value==cat.ToString()).Select(x=>Convert.ToInt32(x.Attribute("owner").Value)).Distinct().ToList();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top