.NET Linq to XML: final value overwrites previous DISTINCT values

I have a query that works fine if it returns a SINGLE string. However, if there are several lines, this will be:

  • create the correct number of rows
  • it is wrong to assign each row the value of the last row ... In this case, it will return x3 rows, since this is the final node that satisfies the request.

I would expect it to return the x3 DISTINCT lines. Can anyone suggest why individual values ​​are 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; } 
+4
source share
1 answer

Move Music music = new Music(); inside the foreach .

You are currently creating one instance of Music and adding it to the list several times. Each time you update it, each item in the list is affected because they are all the same.

+2
source

Source: https://habr.com/ru/post/1445538/


All Articles