正在尋找可以幫助我使用 C#、LINQ 的人。
我有一個Dictionary<int,int>我正在訂購的:.OrderBy(_ => _.Value).ThenBy(_ => ThisMethodReturnsAnotherIReadOnlyDict<int,int>()).ThenByDescending(_ => _.Key)。
我想要的是按其值對第一個字典進行排序,然后如果仍然存在相等的值,我希望該領帶被ThisMethodReturnsAnotherIReadOnlyDict<int,int>(). 這ThisMethodReturnsAnotherIReadOnlyDict是打破平局并處于領先地位的第一個鍵/值。最后,如果一切都失敗了,那么按它的鍵降序排序。
一些資料,例如:
(第一詞典)
[1,400]
[2,550]
[3,200]
[4,200]
(第二詞典)
[3,50]
[4,140]
[2,600]
[1,700]
對于這種情況,我希望我的訂單回傳:[3,50]
有人可以幫忙嗎?謝謝!
uj5u.com熱心網友回復:
看起來你正在尋找這樣的東西:
var firstDict = new Dictionary<int, int>() {
{1,400},
{2,550},
{3,200},
{4,200}
};
var secondDict = new Dictionary<int, int>() {
{3,50},
{4,140},
{2,600},
{1,700}
};
var result = (from kvp in firstDict
join tieBreaker in secondDict on kvp.Key equals tieBreaker.Key
select new { kvp.Key, V1 = kvp.Value, V2 = tieBreaker.Value })
.OrderBy(x => x.V1)
.ThenBy(x => x.V2)
.ThenByDescending(x => x.Key)
.First();
這將通過其鍵將第一個和第二個字典連接在一起,并分別按第一個字典的值、第二個字典的值然后按鍵本身降序排序。
uj5u.com熱心網友回復:
怎么樣:
var ans = firstDict
.OrderBy(kv => kv.Value)
.ThenBy(kv => ThisMethodReturnsAnotherIReadOnlyDict<int,int>().TryGetValue(kv.Key, out var val2) ? val2 : kv.Key)
.ToList();
除非ThisMethodReturnsAnotherIReadOnlyDict<int,int>可能發生變化,否則您可能希望在排序之前將回傳值快取在變數中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/386498.html
上一篇:資料表上的分組依據
