Skip to main content
 首页 » 编程设计

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

2024年02月23日18grandyang

从 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; 
}