簡體   English   中英

如何忽略/刪除linq查詢結果C#中的非數值

[英]How do I ignore/remove non-number values from linq query results C#

我有一個linq查詢,它迭代了數百個XML元素來計算工具集合中使用的特定工具的數量。

但是,工具xelement集合中的qty元素應該包含一個數字,偶爾會包含諸如“As required”之類的文本,而不是特定的數字。 這顯然會導致問題。

是否有一個簡單的附加步驟,我可以放入這個linq查詢(我對linq不好),它會忽略非數字值,還是過濾掉它們?

Linq查詢是:

Dictionary<int, int> dict = listTools.Descendants("tool")
                .GroupBy(x => (int)x.Element("id"), y => (int)y.Element("qty"))
                .ToDictionary(x => x.Key, y => y.Sum());

使用int.TryParse

.GroupBy(x => (int)x.Element("id"), 
         y => int.TryParse(y.Element("qty"), out int qty) ? qty : 0)

來自文檔

如果s參數為null或Empty,格式不正確,或者表示小於MinValue或大於MaxValue的數字,則轉換失敗

嘗試這個:

.GroupBy(x => (int)x.Element("id"), 
         y => 
         {
             int qty = 0;
             if (int.TryParse(y.Element("qty"), out qty))
                 return qty;
             return 0;
         })

暫無
暫無

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

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