的列表中查找最接近的值

的列表中查找最接近的值

本文介绍了使用linq在C#的列表中查找最接近的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

public List<Dictionary<int, int>> blanks { get; set; }

这保留了一些索引值:

此外,我还有一个名为X的变量.X可以取任何值.我想找到最接近X的键"值.例如:

In addition I have also a variable named X. X can take any value. I want to find closest 'Key' value to X. For example:

如果X为1300,我要输入空白索引:2和键:1200.我如何通过linq做到这一点?或者,还有其他解决方案吗?

If X is 1300, I want to take blanks index: 2 and Key: 1200.How can I do this via linq? Or, is there any other solution?

谢谢.

如果它不是字典,该怎么办.如果它是这样的列表怎么办:

What if it is not a Dictionary. What if it is a List like this:

List<List<int[]>> lastList = new List<List<int[]>>();

这次,我要获取第一个List的索引和第二个List的索引.例如,如果X为800,我想取0和0(对于索引0),也想取1和1(对于索引1),我该怎么办?

This time, I want to take first List's indexes and second List's index. For example, if X is 800, I want to take 0 and 0 (for index 0) and also take 1 and 1 (for index 1) How can I do this time?

推荐答案

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}实例的集合.

The SelectMany clause flattens all the dictionaries entries into a collection of { ListIndex, DictionaryKey, Difference } instances.

然后将这个扁平化的集合进行汇总,以检索出差异最小的项目.

This flattened collection is then aggregated to retrieve the item with the minimum 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中,您将找到关闭项目的索引(列表索引,数组索引和数组项目索引)

Now in closestDiff you'll find the indices of the closes item (List index, array index and array item index)

这篇关于使用linq在C#的列表中查找最接近的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:53