2012-02-03 3 views
0

아래 linq to xml 쿼리에는 두 개의 속성 인 list<string>, DefaultValues ​​및 Values가 있습니다.linq to xml 빈 목록 <string> 요소?

이러한 요소 중 하나가 비어있는 경우, 나는 비어있는 새 목록에 LiteValueParameter 객체의 속성을 설정하려는 :

Values = new List<string>(); 

대신, LINQ 쿼리이 아이크 내게 뭔가를주고있다 :

Values = new List<string>(); 
Values.Add(""); 

XML에 빈 요소가있는 경우 빈 항목이 목록에 추가되는 것을 방지 할 수있는 방법이 있습니까?

의 LINQ 코드 :

//linq query 
List<LiteValueParameter> valParams = new List<LiteValueParameter>(); 
valParams = (from c in doc.Descendants("Parameters").Descendants("Parameter") 
      where (LiteParameterType)Enum.Parse(typeof(LiteParameterType), c.Element("ParameterType").Value, true) == LiteParameterType.Value 
      select new LiteValueParameter() 
      { 
       Id = c.Attribute("Id").Value, 
       DataType = Type.GetType(c.Element("DataType").Value, true), 
       DefaultValues = c.Elements("DefaultValues").Select(element => element.Value).ToList(), 
       DisplayText = c.Element("DisplayText").Value, 
       IsRequired = Convert.ToBoolean(c.Element("IsRequired").Value), 
       MinCount = Convert.ToInt32(c.Element("MinCount").Value), 
       MaxCount = Convert.ToInt32(c.Element("MaxCount").Value), 
       MinValue = c.Element("MinValue").Value, 
       MaxValue = c.Element("MaxValue").Value, 
       ParameterName = c.Element("ParameterName").Value, 
       Values = c.Elements("Values").Select(element => element.Value).ToList(), 
       ParameterType = (LiteParameterType)Enum.Parse(typeof(LiteParameterType), c.Element("ParameterType").Value, true), 
       DisplayType = c.Element("DisplayType").Value 
      }).ToList(); 

XML 코드 :

<Parameters> 
    <Parameter Id="PermissionList"> 
    <ParameterType>Value</ParameterType> 
    <ParameterName>Permissions</ParameterName> 
    <DisplayType>ListBox</DisplayType> 
    <DisplayText>Permissions</DisplayText> 
    <IsRequired>true</IsRequired> 
    <MinValue /> 
    <MaxValue /> 
    <DefaultValues /> 
    <Values /> 
    <DataType>System.String</DataType> 
    <MinCount>1</MinCount> 
    <MaxCount>1</MaxCount> 
    </Parameter> 
</Parameters> 
+0

WHERE 절에서 조건을 수정하려고 했습니까? –

답변

4

난 당신이 이런 식으로 해결 될 것 같아요 :

DefaultValues = (c.Elements("DefaultValues").Count() == 1 && c.Elements("DefaultValues").First().Value == string.Empty) ? new List<string>() : 
c.Elements("DefaultValues").Select(element => element.Value).ToList(), 

이러한 접근 방식은 비록 매우 "해키"느낀다. 대신 나는 당신이 대신 쿼리 DefaultValue 요소가 당신의 XML을 변경합니다 :

<DefaultValues> 
    <DefaultValue>Foo</DefaultValue> 
</DefaultValues> 

이 훨씬 더 자연과

DefaultValues = c.Descendants("DefaultValue").Select(element => element.Value).ToList(), 

이 빈 컬렉션을 반환합니다처럼 지금 당신은 당신의 쿼리를 작성할 수 있습니다 방금 가지고있는 경우

<DefaultValues/> 
+0

'c.Descendants ("DefaultValue")를 사용하면 효과가 있습니다. 감사! – ChandlerPelhams