有趣的問題在這里。我正在嘗試按數值對a進行排序。它適用于但不是,我在這里做錯了什么?Dictionary<string, string>List<string>Dictionary
Dictionary<string, string> s = new Dictionary<string, string>() {
{ "a", "a" },
{ "100", "1" },
{ "2", "2" },
{ "10", "10" },
};
List<string> g = new List<string> {
"1", "10", "a", "1000"
};
var v = 0;
var problem = s.OrderBy(x => int.TryParse(x.Key, out v));
// outputs original order
var works = from c in g
orderby int.TryParse(c,out v)
select c;
// outputs sorted order a, 1, 10, 1000
uj5u.com熱心網友回復:
您需要了解兩個截然不同的巨大問題。
- 您不是按 v 排序。您是按傳遞給 OrderBy 呼叫的比較器回傳的任何內容進行排序,在您的示例中它是一個布林值。所以,你正在這樣做:
var g = new List<string> { "1", "10", "a", "1000" };
var works = from c in g
orderby int.TryParse(c,out v)
select c;
// It doesn't work, because int.TryParse outputs [true, true, false, true]
// which is used as a sorting key, which puts the 'a' as the first element,
// because false is sorted before true.
// try with this input:
var g = new List<string> { "10", "1", "a", "1000" };
// and you'll see that the output is ["a", "10", "1", "1000"]
所以,你的排序功能應該是int.TryParse(c,out v) ? v : -1. 如果您還需要對無效鍵進行排序,-1則可能會有所不同,但這可以ThenBy通過OrderBy.
但是,您仍然有一個重大錯誤:
- 您總是在更新單個變數
v。如果計算該值并將其存盤在共享變數中,則很容易導致后期評估出現問題,因此您應該var v從外部范圍中洗掉并使用
// the addition of 'var' in the out declaration enables the usage of a separate, new v for each item in the source,
// thus removing the possibility of collisions.
s.OrderBy(x => int.TryParse(x.Key, out var v) ? v : -1);
// if you need to put the alphanumeric keys last, and maybe sorting
// them alphabetically, you can also use something like:
s.OrderBy(x => int.TryParse(x.Key, out var v) ? v : int.MaxValue)
.ThenBy(x => x) // sorts by the string itself
;
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
var problem = s
.OrderBy(pair => int.TryParse(pair.Key, out var parsed)
? parsed // Take Key value as it is
: long.MinValue); // Treat pair as the topmost
在這里我們嘗試Key從鍵值中決議pair,如果我們失敗了,我們把它放在最上面(我用long.MinValue它來與可能的int.MinValue鍵混合)。您可能要添加.ThenBy:
var problem = s
.OrderBy(pair => int.TryParse(pair.Key, out var parsed)
? parsed // Take Key value as it is
: long.MinValue) // Treat pair as the topmost
.ThenBy(pair => pair.Key);
如果您想對非數字鍵以及數字進行排序,例如
Dictionary<string, string> demo = new() {
{ "a", "a" },
{ "100", "1" },
{ "2", "2" },
{ "b", "a" },
{ "10", "10" },
{ "c", "a" },
};
var result = demo
.OrderBy(pair => int.TryParse(pair.Key, out var parsed)
? parsed
: long.MinValue)
.ThenBy(pair => pair.Key);
Console.Write($"{string.Join(Environment.NewLine, result)}");
輸出:
[a, a]
[b, a]
[c, a]
[2, 2]
[10, 10]
[100, 1]
編輯:如果你想把數字放在第一位,你應該做的就是long.MinValue改變long.MaxValue:
var result = demo
.OrderBy(pair => int.TryParse(pair.Key, out var parsed)
? parsed
: long.MaxValue)
.ThenBy(pair => pair.Key);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496876.html
上一篇:在字典中填充層次結構
下一篇:根據python中的條件拆分字典
