如果返回SINGLE行,我的查询工作正常。但是,如果有多行,则会:
我原以为它会返回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;
}
答案 0 :(得分:2)
在Music music = new Music();
循环中移动foreach
。
目前,您正在创建单个Music
实例,并将其多次添加到列表中。每次更新时,列表中的每个项目都会受到影响,因为它们都是相同的项目。