In the linq to xml query below, I have 2 properties that are a list<string>, DefaultValues and Values.
If either of these elements are empty, I would like to set that property of the LiteValueParameter object to a new, empty list:
Values = new List<string>();
Instead, the linq query is giving me something lke this:
Values = new List<string>();
Values.Add("");
Is there any way to prevent an empty item being added to the list if I have an empty element in my XML?
Linq code:
//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 Code:
<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>
I suppose you could work around it like this:
This approach feels very “hacky” though. Instead I would change your XML to have a
DefaultValueelement that you query instead:This is much more natural and now you can just write your query like
This will return an empty collection if you just have