如何使用嵌套的ObservableCollection将数据LINQ数据导入ObservableCollection?

时间:2011-03-01 20:15:25

标签: c# linq mvvm windows-phone-7 windows-phone

从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();

2 个答案:

答案 0 :(得分:3)

像下面这样的事情可以解决问题:

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

答案 1 :(得分:1)

这应该是直截了当的 - 只需在select中执行另一个嵌套的LINQ查询 - 然后可以使用带有IEnumerable的ObservableCollection构造函数。

为了保持理智,您可能希望将其分解为单独的功能!