C#XML ToList内部ToList

C#XML ToList内部ToList,c#,xml,silverlight,tolist,C#,Xml,Silverlight,Tolist,我有下面的C#代码,我不知道为什么它不工作(我得到了一个NullReferenceException错误)。如果我将Recipe定义为new List(),一切都开始正常工作 foreach (XElement element in document.Descendants("vegetables")) { VegetablesList = ( from vegetables in element.Elements()

我有下面的C#代码,我不知道为什么它不工作(我得到了一个NullReferenceException错误)。如果我将Recipe定义为new List(),一切都开始正常工作

foreach (XElement element in document.Descendants("vegetables"))
        {
            VegetablesList = (
                from vegetables in element.Elements()
                select new FoodItem()
                {
                    Name = (vegetables.Element("name") == null) ? null : vegetables.Element("name").Value.ToString(),
                    Bcg = (vegetables.Element("bcg") == null) ? null : vegetables.Element("bcg").Value.ToString(),
                    Info = (vegetables.Element("info") == null) ? null : vegetables.Element("info").Value.ToString(),
                    Recipes = (
                        from recipes in element.Element("recipes").Elements()
                        select new Recipe()
                        {
                            Name = (recipes.Element("name") == null) ? null : recipes.Element("name").Value.ToString(),
                            Text = (recipes.Element("text") == null) ? null : recipes.Element("text").Value.ToString()
                        }
                    ).ToList()
                }
            ).ToList();
            VegetablesListBox.ItemsSource = VegetablesList;
        }

谢谢你的帮助

我的猜测是
element.element(“recipes”)
返回
null
,这意味着
recipes
元素在该迭代中不存在。

哪一行代码给出了null引用异常?为什么反复将
VegetablesList
分配给
ItemsSource
?顺便使用
Name=(string)recipes.Element(“name”)
这将使您的代码更易于阅读。我在new FoodItem(){…}@AnthonyWJones上遇到错误,我只分配VegetablesListBox.ItemsSource=VegetablesList;-这有什么问题吗?谢谢!通过将Element.Element(“recipes”).Elements()更改为vegets.Element(“recipes”).Elements()来修复Null是Linq to XML中的一个麻烦。我一直在与之抗争。@Robert Harvey-Linq实际上非常清楚地告诉您代码有问题,这不是很好吗?而不是只是默默地返回空集合,使您的问题很难调试?!好吧,我最后为您编写了一些扩展方法短路所有null并返回空集合。在调用每个返回的对象上的方法之前,检查其是否为null太困难了。除非总是返回活动对象,否则几乎不可能链接
元素()
子体()
方法,这就是我想要做的。