Reputation: 338
I have an XML response structured as follow:
<e:Parents>
<d1p1:Parent>
<d1p1:Name>A</d1p1:Name>
<d1p1:Child>a1</d1p1:Child>
<d1p1:Id>101</d1p1:Id>
</d1p1:Parent>
<d1p1:Parent>
<d1p1:Name>A</d1p1:Name>
<d1p1:Child>a2</d1p1:Child>
<d1p1:Id>102</d1p1:Id>
</d1p1:Parent>
<d1p1:Parent>
<d1p1:Name>B</d1p1:Name>
<d1p1:Child>b1</d1p1:Child>
<d1p1:Id>201</d1p1:Id>
</d1p1:Parent>
<d1p1:Parent>
<d1p1:Name>B</d1p1:Name>
<d1p1:Child>b2</d1p1:Child>
<d1p1:Id>202</d1p1:Id>
</d1p1:Parent>
</e:Parents>
Now based on the given input (e.g. A a2) I need to fetch the id (e.g. 102).
In my function I am trying to use something as such
int getId(string str) // str = A a2
{
int index = str.IndexOf(' ');
string p = str.Substring(0, index); //A
string c = str.Substring(index); //a2
var parent = response.Parents.FirstOrDefault(e => e.Name == p && e.Child == c);
return parent.Id;
}
It gives me an error which says:
"The type arguments for method 'System.Linq.Enumerables.FirstOrDefault(System.Collections.Generics.IEnumerable,System.Func)' cannot be inferred from the usage. Try specifying arguments explicitly."
I need to know how can I get the Id based on Parent and Child.
Upvotes: 0
Views: 63
Reputation: 19081
The following Linq expression should give you the value you are looking for:
XElement xmlSet = XElement.Parse (yourXmlStringHere);
// Will contain the <parent>..</parent> you want
var parentNode =
xmlSet.Elements("d1p1:Parent")
.First(e => e.Elements("d1p1:Name").First().Value == "B"
&& e.Elements("d1p1:Child").First().Value == "a2");
// This will fetch the value - 102 in this case:
var value = parentNode.Elements("d1p1:Id").First().Value;
Upvotes: 1