[英]How do I fix my linq query
這是示例XML
<?xml version="1.0" encoding="utf-8" ?>
<Instructions>
<Instruction>
<Brand>Brand1</Brand>
<Text>
this is text for Brand1
</Text>
</Instruction>
<Instruction>
<Brand>Brand2</Brand>
<Text>
Brand2 text is slightly different
</Text>
</Instruction>
<Instruction>
<Brand>Brand3</Brand>
<Text>
Brand3 has boring text
</Text>
</Instruction>
<Instruction>
<Brand>Brand4</Brand>
<Text>
Brand4 had long text until the editor got hold of this file
</Text>
</Instruction>
</Instructions>
我的代碼是這樣的:
string WhoAmI = "Brand1";
string t =
(from Instruction in xmlDoc.Descendants("Instruction")
where (string)Instruction.Element("Brand").Value == WhoAmI
select t = Instruction.Element("Text").Value
).ToString();
//end code
t總是
System.Linq.Enumerable + WhereSelectEnumerableIterator`2 [System.Xml.Linq.XElement,System.String]
不
這是Brand1的文字
我究竟做錯了什么?
LINQ語句返回一個值序列,而不是單個值。 因此,通常在序列對象上調用.ToString()
不會給您任何特別有用的東西。
在這種情況下,您的語句返回的序列中包含一個值,但仍然是一個序列。 因此,您需要編寫僅返回一個值的LINQ語句:
string t = (from ... select ...).First();
這里還需要考慮其他含義,例如,如果序列為空,則First()
將引發異常。 FirstOrDefault()
將改為返回null。
嘗試用FirstOrDefault()
替換ToString()
FirstOrDefault()
該查詢將返回一個字符串序列,而不是單個字符串。 因此,.ToString()方法調用將是IEnumerable ToString方法。
如果您確信查詢將始終只返回1個字符串,則可以使用Single()或SingleOrDefault()方法僅返回字符串。
string WhoAmI = "Brand1";
string t =
(from Instruction in xmlDoc.Descendants("Instruction")
where (string)Instruction.Element("Brand").Value == WhoAmI
select t = Instruction.Element("Text").Value
).SingleOrDefault();
這將為您提供Text節點包含的文本值的集合。 但是,如果缺少“文本”節點或“品牌”節點,則此查詢將失敗。 您發布的代碼正在執行的操作是不接受結果。 您正在將收集對象強制轉換為返回的字符串,該字符串默認情況下僅為您提供對象的名稱。
您將需要遍歷查詢返回的列表,以對返回的多個值執行有用的操作...
var results = (from e in doc.Descendants("Instruction")
where e.Descendants("Brand").First().Value == WhoAmI
select e.Descendants("Text").First().Value).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.