2

私はLINQを学んでいて、select句に関連するこの例を試していました。

var q = from c in xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

上記のクエリは私にエラーを与えています:
The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

上記の構文で何が間違っていますか?

上記とは別に、selectedオプションを変換する必要がありますToDictionary。LINQ を介して同じクエリでどのように実行できますか?

私が頭に浮かんだ 3 番目の質問は、同じクエリを記述するための異なる構文についてでした (e: 以下の 2 番目のメソッドの記述例)。優先される構文とその理由は?

from c in xmlDoc.Descendants
where c.Attriubute("technical").Value == "true"
select c.Element("site").Value;
4

1 に答える 1

3

1.ラムダ式とlinq構文を混在させました。linqで始まり、ラムダ式で終わります。これを試して

 var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value});

または、linqでクエリ全体を使用する必要があります

var q = from c in xmlDoc.Descendants("site") where c.Attribute("technical").Value == "true"
                   select new { SiteName = c.Element("name").Value};

2.クエリの最後にToDictionaryを使用するだけです

var q = xmlDoc.Descendants("site").Where(tech => tech.Attribute("technical").Value == "true")
                   .Select(n => new { SiteName = n.Element("name").Value,Key= n.Element("id").Value }).ToDictionary(n=>n.Key,l=>l.SiteName);

n => n.Keyは辞書のキーになり、l=>l.siteNameは値になります。

3.このようなクエリを作成する方法は2つあります。1つはlinqを使用する方法、もう1つはラムダ式をパラメーターとして使用するメソッドを使用する方法です。どちらも簡単です。linqはSQLクエリに似ていますが、メソッドはラムダを使用し、記述メソッドでデータを操作するための速記に似ています。私は個人的に、ラムダをより順次読みやすい方法指向の方法が好きです。

于 2012-06-20T05:24:38.997 に答える