我是LINQ的新手.我需要List
使用xml中的信息填充以下类中的一个.
class Person
{
int id;
string name;
string address;
}
List<Person> people = new List<Person>();
Run Code Online (Sandbox Code Playgroud)
在LINQ中执行此操作的正确方法是什么.
<Company>
...
...<!--Lot of items -->
...
<People> <!--People appears only once -->
<Instance>
<ID>1</ID>
<Name>NameA</Name>
<Address>AddressA</Address>
</Instance>
<Instance>
<ID>2</ID>
<Name>NameB</Name>
<Address>AddressB</Address>
</Instance>
..
..
</People>
</Company>
Run Code Online (Sandbox Code Playgroud)
我需要知道LINQ表达式的结构才能直接到达<People>
标签.此外,是否有任何用于填写List', i.e map
Person to
Instance`标签的快捷方式.
我希望您知道,您需要将您的字段(或更好地使它们属性)设置为公共,以便能够填充对象值.您在类字段中缺少公共修饰符.
var doc = XDocument.Parse(xmlString);
List<People> people = doc.Descendants("People")
.FirstOrDefault()
.Descendants("Instance")
.Select(p=> new Person()
{
ID = p.Element("ID").Value,
Name = p.Element("Name").Value,
Address=p.Element("Address").Value
}).ToList();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2442 次 |
最近记录: |