gpt4 book ai didi

c# - 如何使用嵌套的 ObservableCollection 将数据 LINQ 到 ObservableCollection 中?

转载 作者:太空宇宙 更新时间:2023-11-03 22:16:01 26 4
gpt4 key购买 nike

从 xml 中执行 ViewModel 的最佳方法是什么:

<Cars>
<Car>
<Name/>
<Model/>
<Parts>
<Part>
<PartName/>
<PartType/>
</Part>
<Part>
<PartName/>
<PartType/>
</Part>
</Parts>
</Car>
</Cars>

会不会是这样

public class PartViewModel : INotifyPropertyChanged
{
private string _PartName;
private string _PartType;
//... and proper get/seters for NotifyPropertyChanged
};

public class CarViewModel : INotifyPropertyChanged
{
private string _Name;
private string _Model;
private ObservableCollection<PartViewModel> _parts;
//... and proper get/seters for NotifyPropertyChanged
};

那么 LINQ 将如何填充 CarViewModel ?

 List<CarViewModel> FeedItems = (from carsXdoc in xdoc.Descendants("Cars")
select new CarViewModel()
{
Name = carsXdoc.Element("Name").Value,
Model = carsXdoc.Element("Model").Value,
// And then ? how do you fill nested observable collection with parts ?
}).ToList();

最佳答案

像下面这样的东西应该可以解决问题:

List<CarViewModel> FeedItems = (from carsXdoc in xdoc.Descendants("Cars")
select new CarViewModel()
{
Name = carsXdoc.Element("Name").Value,
Model = carsXdoc.Element("Model").Value,
Parts = ToObservableCollection(from part in carsXdoc.Element("Parts").Descendants("Part")
select new PartViewModel()
{
PartName = part.Element("PartName").Value,
PartType = part.Element("PartType").Value,
})
}).ToList();

ToObservableCollection() 方法:

ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> sequence)
{
ObservableCollection<T> collection = new ObservableCollection<T>();
foreach (var item in sequence)
{
collection.Add(item);
}

return collection;
}

关于c# - 如何使用嵌套的 ObservableCollection 将数据 LINQ 到 ObservableCollection 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5159807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com