3

私のクエリの戻り値はIEnumerable<XElement>です。XElement結果のデータをタイプに変換するにはどうすればよいですか?出来ますか?誰かが私がこれを理解するのを助けることができますか?

var resQ = from e in docElmnt.Descendants(xmlns + Constants.T_ROOT)
                             .Where(x => x.Attribute(Constants.T_ID).Value == "testid") 
           select e;

以下の関数にパラメーターとしてresQを渡す必要があります。そのためには、resQをXElementタイプに変換する必要があります。

Database.usp_InsertTestNQuestions(tid, qId, qstn, ans, resQ ); 
4

3 に答える 3

8

クエリが単一の結果のみを返す限り、結果に対してSingle()またはFirst()を呼び出すことができます(また、追加のクエリ構文は必要ありません)。

// Use if there should be only one value.
// Will throw an Exception if there are no results or more than one.
var resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Single(x => x.Attribute(Constants.T_ID).Value == "testid");

// Use if there could be more than one result and you want the first.
// Will throw an Exception if there are no results.
var resQ = docElmnt.Descendents(xmlns + Contants.T_ROOT)
                   .First(x => x.Attribute(Constants.T_ID).Value == "testid");

例外をスローせずにクエリの結果が返されない場合を処理する場合は、SingleOrDefault(複数の結果を取得した場合でも例外をスローします)またはを使用できますFirstOrDefault

于 2010-08-27T18:42:46.193 に答える
1

Justinの答えに加えて、0個の要素が返されるか他の条件を許可したい場合があります。

その場合は、次のようにしてください。

IEnumerable<XElement> resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Where(x => x.Attribute(Constants.T_ID).Value == "testid");
if(resQ.Count() == 0) {
  //handle no elements returned
} else if(resQ.Count() > 1) {
  //handle more than 1 elements returned
} else {
  XElement single = resQ.Single();
}

ほとんどの場合、エラーをスローしないことが最善だと思います。ただし、正確に1つを返すことが本当に重要でない限りです。

于 2010-08-27T18:55:03.117 に答える
1

クエリ内の各要素を繰り返し処理してから、列挙子を使用してメソッドを呼び出すことができます。

resQ.ToList().ForEach(e => ...func... );
于 2010-08-27T18:44:52.557 に答える