I am getting following error
Cannot implicitly convert type
'System.Collections.Generic.List<AnonymousType#1>' to
'System.Collections.Generic.List<string>'
I tried reading similar questions on stack overflow but didn't find a solution. My code is as below
var head =
from key in doc.Descendants("Header").Descendants("Article")
select new
{
value = (key.Value == String.Empty ?
from q in doc.Descendants("Header").Descendants("Article") select q.Value : from a in doc.Descendants("Header").Descendants("Article")
select a.Attribute("DefaultValue").Value)
};
List<string> hsourceFields = head.ToList();
If the value of xml node is empty I am reading the default value specified for that xml node
<Header>
<Article>News</Article>
<Article DefaultValue ="Sport"></Article>
</Header>
I want to be able to return a List which I am not able to by getting the error.
Looks like your code was getting a List<AnonType{value = List<string>}>
instead of a List<string>
I think you want something like this that will select the text from an article or if that is empty it will take the value of the DefaultValue attribute. Note this doesn't handle when there is no text and no attribute.
var head =
from key in doc.Descendants("Header").Descendants("Article")
select
string.IsNullOrEmpty(key.Value) ?
key.Attribute("DefaultValue").Value :
key.Value;
List<string> hsourceFields = head.ToList();
Or a slightly abbreviated version that uses xpath and method chains
var hsourceFields = doc.XPathSelectElements("/Header/Article")
.Select (x => string.IsNullOrEmpty(x.Value) ?
x.Attribute("DefaultValue").Value :
x.Value).ToList()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments