繁体   English   中英

使用linq在C#的列表中查找最接近的值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM