如何将这两个不同的LINQ查询合并为一个?

时间:2014-07-07 01:09:06

标签: c# xml linq-to-xml

如何编写此代码以便我可以在一个查询中获取Id和Fist以及姓氏?我通过搜索找到的所有内容都与数据库相关,涉及加入或群组,我认为这不适用于我想要做的事情。我想在屏幕上打印订单ID以及相关的名字和姓氏。

   static void Main()
    {
        XDocument document = XDocument.Parse(GetXml());

        var query = from el in document.Root.Elements("Order")
                    select new Orders
                    {
                        Id = (int)el.Element("Id")
                    };

        foreach (var cc in query)
        {
            Console.WriteLine(cc.Id);

        }

        var info = from el in document.Root.Elements("Order").Elements("BillingAddress")
                   select new BillingAddress
                   {
                       FirstName = (string)el.Element("FirstName"),
                       LastName = (string)el.Element("LastName")
                   };

        foreach (var cc in info)
        {
            Console.WriteLine("{0} {1}", cc.FirstName, cc.LastName);
        }

        Console.ReadLine();
    } 

    private static String GetXml()
    {
        return
            @"<ArrayOfOrder>
                <Order>
                    <Id>1</Id>
                    <OrderGuid />
                    <BillingAddress>
                        <FirstName>Harvey</FirstName>
                        <LastName>Danger</LastName>
                    </BillingAddress>
                </Order>
                <Order>
                    <Id>2</Id>
                    <OrderGuid />
                    <BillingAddress>
                        <FirstName>Brian</FirstName>
                        <LastName>Brakes</LastName>
                    </BillingAddress>
                </Order>
            </ArrayOfOrder>";
    }    

2 个答案:

答案 0 :(得分:1)

BillingAddress属性添加到Orders类,然后您可以执行以下操作:

var query = from el in document.Root.Elements("Order")
            select new Orders
            {
                Id = (int) el.Element("Id"),
                BillingAddress = new BillingAddress
                {
                    FirstName = (string) el.Element("BillingAddress").Element("FirstName"),
                    LastName = (string) el.Element("BillingAddress").Element("LastName")
                }
            };

答案 1 :(得分:0)

var query = from el in document.Root.Elements("Order")
                    select new Orders
                    {
                        Id = (int)el.Element("Id"),
                        Names = el.Elements("BillingAddress")
                                  .Select(ba=> 
                                        new { FirstName = (string)ba.Element("FirstName"),
                                              LastName = (string)ba.Element("LastName")
                                            }
                    };