簡體   English   中英

從 LINQ 到 XML 查詢中獲取單個字符串

[英]Get a single string from a LINQ to XML query

這是我想做的事情:

string parseCode = from x in xml.Descendants("LogType")
                   where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
                   select x.Attribute("ParseCode").Value;

但這會產生錯誤: “無法將類型'System.Collections.Generic.IEnumerable'隱式轉換為'字符串'”

x.Attribute("ParseCode")只有一個值,但它堅持返回類型IEnumerable<string> 如何將該值提取到字符串中?

編輯:感謝您的回復。 這對我有用:

string parseCode = (from x in xml.Descendants("LogType")
                    where x.Attribute("ID").Value == (string) ddlHistoryLogDefinitions.SelectedValue
                    select (string) x.Attribute("ParseCode").Value).FirstOrDefault();

這個技巧是將整個 linq 查詢包裝在 .FirstOrDefault() 之前的 () 中。

使用.Single到 select 唯一的結果,如果你知道只有一個:

string parseCode = (from x in xml.Descendants("LogType")
                   where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
                   select x.Attribute("ParseCode").Value).Single();

使用.SingleOrDefault.First如果可能沒有或更多則分別。

您查詢返回一個集合。 如果您需要第一個找到的LogType節點,則可以執行以下操作:

string parseCode = xml.Descendants("LogType")
    .Where(x => x.Attribute("ID").Value == (string)ddlHistoryLogDefinitions.SelectedValue)
    .Select(arg => x.Attribute("ParseCode").Value)
    .FirstOrDefault();

如果沒有找到元素,將返回null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM