I have a query thatworks fine if it returns a SINGLE row.However, if there are multiple rows, it will:
- create the correct quantity of rows
- incorrectly assign each row to the value of the final row…In this case, it will return x3 rows of , as this is the final node that satisfies the query.
I’d have expected it to return x3 DISTINCT rows.
Can anyone suggest why the distinct values are being overwritten by the final xml node?
Thanks
<?xml version="1.0" encoding="utf-8" ?>
<Music>
<customer id="89">
<name value="Sample Name 2" />
<age value="31" />
<location>
<city value="Wichita" />
<state value="KS" />
<country value="USA" />
</location>
</customer>
<customer id="80">
<name value="Sample Name 3" />
<age value="41" />
<location>
<city value="Seattle" />
<state value="WA" />
<country value="USA" />
</location>
</customer>
<customer id="84">
<name value="Sample Name" />
<age value="29" />
<location>
<city value="Los Angeles" />
<state value="CA" />
<country value="USA" />
</location>
</customer>
<customer id="100">
<name value="Rock UK" />
<age value="25" />
<location>
<city value="Los Angeles" />
<state value="CA" />
<country value="USA" />
</location>
</customer>
</Music>
The code is as follows:
private List<Music> currentMusic { get; set; }
private IEnumerable<Music> GetCustomer(string id)
{
XElement main = XElement.Load(@"D:\work\web\App_Data\Customers.xml");
IEnumerable<XElement> searched =
from c in main.Elements("customer")
where (string)c.Attribute("id") != "100"
select c;
Music music = new Music();
currentMusic = new List<Music>();
foreach (XElement customer in searched)
{
music.Country = customer.Element("name").Attribute("value").Value;
music.Name = customer.Element("age").Attribute("value").Value;
currentMusic.Add(music);
}
return currentMusic;
}
Move
Music music = new Music();inside yourforeachloop.At the moment you’re creating a single
Musicinstance and adding it to the list multiple times. Every time you update it, every item in the list is affected because they’re all the same item.