I'm trying to convert this VB.Net LINQ to C# LINQ.
Basically, what the end solution is trying to achieve is to to take in an XML file; see snippet:
<BasicFee>
<TrialType>Trial</TrialType>
<A>1326.85575</A>
<B>992.409</B>
<C>668.67075</C>
<D>1260.50925</D>
<E>318.8955</E>
<F>323.30925</F>
<G>323.30925</G>
<H>323.44125</H>
<I>323.169</I>
<J>1326.85575</J>
<K>932.877</K>
</BasicFee>
And by passing parameters, "Trial" and "B", the result would give me this value "992.409" (result from Trial / B).
EDIT - This VB is not the correct syntax to achieve the result. Please see the accepted answer.
The VB equivalent is apparently something like this;
Dim sResult As String = (From oRecord In oXML.Descendants("BasicFee") Where oRecord.< Name >.Value = "Trial").FirstOrDefault.< B >.Value
I have tried tons of different ways and I keep getting the same result (either the Trial element OR the A element values (not being able to use them both).
I was hoping there would be something similar to this:
var example = root.Elements("BasicFee").Elements().Where((c=>c.Value == "Trial" && c.Value == "A"));
Any ideas?
Thanks.
As noted in comments, your VB example wouldn't work either, but it's pretty simple to do in both languages. You need to distinguish between names and values, and exactly how your filtering works:
var example = root.Elements("BasicFee")
.Where(x => (string) x.Element("TrialType") == "Trial")
.Select(x => (string) x.Element("B"))
.FirstOrDefault();
Or with C# 6 you could use:
var example = root.Elements("BasicFee")
.FirstOrDefault(x => (string) x.Element("TrialType") == "Trial")
?.Element("B")?.Value;
The value will be null
if there's no such element (either no matching BasicFee
or no B
element within it).
See more on this question at Stackoverflow