根据条件在Linq中选择新的

时间:2018-09-13 12:49:11

标签: c# xml linq

我绝对是Linq的菜鸟,我想尝试使用Linq实现我要完成的任务。我目前正在尝试从XML文件创建对象,并尝试填充应接受不同类(多态性)的列表。

所以我正在努力实现这样的目标... 我有一个像这样的XML文档:

<Quiz>
<Questions>
    <Question number='1' type='Simple' bone='Tibia'>
        <Choices>
            <Choice label='A'>This is choice A.</Choice>
            <Choice label='B'>This is choice B.</Choice>
            <Choice label='C'>This is choice C.</Choice>
            <Choice label='D'>This is choice D.</Choice>
        </Choices>
        <Answer label = 'A'/>
    </Question>
    <Question number='1' type='Complex' bone='Fibula'>
        <Choices>
            <Choice label='A' region='x'>This is choice A.</Choice>
            <Choice label='B' region='x'>This is choice B.</Choice>
            <Choice label='C' region='x'>This is choice C.</Choice>
            <Choice label='D' region='x'>This is choice D.</Choice>
        </Choices>
        <Answer label = 'A'/>
    </Question>
</Quiz>

我的代码如下所示

XDocument xml = XDocument.Load(@filename);
  List<Question> Questions =  (from e in xml.Root.Elements("Question")
                               if (string)e.Attribute('type').Equals('Simple') // Something like this condition
                               select new SimpleQuestion 
                               {
                                 Bone = (string)e.Attribute('bone'),
                                 Answer = (string)e.Elements('Answer').Attribute('label'),
                                 // do something
                               }
                               if (string)e.Attribute('type').Equals('Complex') // Or this condition
                               select new ComplexQuestion
                               {
                                 // do something
                               }
                              ).ToList();

我想知道是否有可能以某种方式允许我选择不同类型的对象的语句或条件。谢谢!

1 个答案:

答案 0 :(得分:0)

我通常使用字典来解析xml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            var dict = doc.Descendants("Question")
                .GroupBy(x => (int)x.Attribute("number"), y => new {
                      type = (string)y.Attribute("type"),
                      bone = (string)y.Attribute("bone"),
                      answer = (string)y.Element("Answer").Attribute("label"),
                      choices = y.Descendants("Choice").GroupBy(a => (string)a.Attribute("label"), b => new KeyValuePair<string,string>((string)b.Attribute("region"),(string)b))
                          .ToDictionary(a => a.Key, b => b.FirstOrDefault())
                }).ToDictionary(x => x.Key, y => (object)y.FirstOrDefault());

        }
    }
}