我有一个查询,如果它返回一个单行,工作正常.但是,如果有多行,它将:
>创建正确的行数
>错误地将每一行分配给最后一行的值…在这种情况下,它将返回x3行,因为这是满足查询的最终节点.
我原以为它会返回x3 DISTINCT行.
任何人都可以建议为什么最终的xml节点会覆盖不同的值?
谢谢
<?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>
代码如下:
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;
}
最佳答案 移动音乐音乐=新音乐();在你的foreach循环中.
目前,您正在创建单个音乐实例并将其多次添加到列表中.每次更新时,列表中的每个项目都会受到影响,因为它们都是相同的项目.