2

次のコードは機能しますが、1 つのクエリで要素 "triptype" と "description" の個別の値をリストに挿入するという同じ結果を達成したいと考えています。どんな助けでも大歓迎です。

前もってありがとう、マルセロ

class Program
{
    static void Main(string[] args)
    {
        string xml = @"<Trips>
                      <Trip>
                        <triptype>vacation</triptype>
                        <description>Trip to Bahamas</description>
                        <id>89</id>
                      </Trip>
                      <Trip>
                        <triptype>vacation</triptype>
                        <description>Trip to California</description>
                        <id>75</id>
                      </Trip>
                      <Trip>
                        <triptype>business</triptype>
                        <description>Trip to Chicago</description>
                        <id>82</id>
                      </Trip>
                    </Trips>";

        List<string> trips = new List<string>();

        XDocument xdoc = XDocument.Parse(xml);

        var tripTypes = (from t in xdoc.Descendants("Trip")
                             .Elements("triptype")
                      select t.Value).Distinct();

        foreach (var tripType in tripTypes)
        {
            trips.Add(tripType);
        }

        var tripDescriptions = (from t in xdoc.Descendants("Trip")
                                    .Elements("description") 
                                select t.Value).Distinct();

        foreach (var tripDescription in tripDescriptions)
        {
            trips.Add(tripDescription);
        }

        Console.ReadLine();

    }
}
4

1 に答える 1

2

私の知る限り、個別の値で達成しようとしているように、単一の LINQ to XML クエリで複数の要素を選択する方法はありません。

ただし、各要素の値を使用してシーケンスを匿名型に射影し、個別の値を見つけることもできますが、それはおそらくやり過ぎで、現在行っていることよりも理解しにくいと思います。つまり、

var query = xdoc.Root.Elements( "Trip" )
        .Select( x => new
                      {
                              trip = x.Element( "triptype" ).Value,
                              desc = x.Element( "description" ).Value
                      } ).ToList();

trips.AddRange( query.Select( x => x.trip ).Union( query.Select( x => x.desc ) ).Distinct() );

代わりに、ループの代わりにList.AddRangeを使用してわずかなクリーンアップを提案し、foreach必要な各ノードの個別の値のセットを取得することで、現在使用しているものと同じロジックを使用します。

var q1 = xdoc.Descendants( "triptype" ).Select( x => x.Value ).Distinct();
var q2 = xdoc.Descendants( "description" ).Select( x => x.Value ).Distinct();
trips.AddRange( q1.Union( q2 ) );
于 2013-03-28T16:00:17.417 に答える