[英]Find closest value in a list in C# with linq?
我有一個這樣的清單:
public List<Dictionary<int, int>> blanks { get; set; }
這保留了一些索引值:
此外,我還有一個名為X的變量。X可以取任何值。 我想找到最接近X的“鍵”值。例如:
如果X為1300,我想使用空白索引:2和鍵:1200。如何通過linq執行此操作? 或者,還有其他解決方案嗎?
提前致謝。
編輯:如果不是字典怎么辦。 如果是這樣的列表怎么辦:
List<List<int[]>> lastList = new List<List<int[]>>();
這次,我要獲取第一個List的索引和第二個List的索引。 例如,如果X是800,我想取0和0(對於索引0),也想取1和1(對於索引1),我該怎么辦?
var diffs = blanks.SelectMany((item, index) => item.Select(entry => new
{
ListIndex = index, // Index of the parent dictionary in the list
Key = entry.Key, // Key
Diff = Math.Abs(entry.Key - X) // Diff between key and X
}));
var closestDiff = diffs.Aggregate((agg, item) => (item.Diff < agg.Diff) ? item : agg);
Dictionary<int, int> closestKeyDict = blanks[closestKey.ListIndex];
int closestKey = closestDiff.Key;
int closestKeyValue = closestKeyDict[closestKey];
SelectMany子句將所有詞典條目展平到{ListIndex,DictionaryKey,Difference}實例的集合中。
然后將這個扁平化的集合進行匯總,以檢索差異最小的項目。
回答第二個問題:
var diffs = blanks.SelectMany((list, listIndex) => list.
SelectMany((array, arrayIndex) => array.
Select((item, itemIndex) => new
{
ListIndex = listIndex,
ArrayIndex = arrayIndex,
ItemIndex = itemIndex,
Diff = Math.Abs(item - X)
})));
var closestDiff = diffs.Aggregate((agg, item) => (item.Diff < agg.Diff) ? item : agg);
現在,在closestDiff
您將找到關閉項的索引(列表索引,數組索引和數組項索引)
這可能不是最優化的方法,但它應該可以工作,
List<Dictionary<int, int>> blanks = new List<Dictionary<int, int>>
{
new Dictionary<int, int>{{100,200}},
new Dictionary<int, int>{{500,200}},
new Dictionary<int, int>{{700,200}},
new Dictionary<int, int>{{1200,200}},
new Dictionary<int, int>{{300,200}},
new Dictionary<int, int>{{200,200}},
new Dictionary<int, int>{{800,200}},
};
int x = 1300;
IEnumerable<int> keys = blanks.SelectMany(ints => ints.Keys);
var diff = keys.Select(i => Math.Abs(i - x)).ToList();
var index = diff.IndexOf(diff.Min());
var value = blanks[index].Keys.First();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.