使用linq在C#列表中查找最接近和较小的值? [英] Find closest and smaller value in a list in C# with linq?

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

问题描述

我有一个这样的列表:

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

这将保留一些索引值:

另外我有也是一个名为X. X的变量可以取任何值。我想找到最接近和更小的'Key'值给X.我可以通过这个代码块只能获取最接近的值。但是,它不能采取较小的一个。

In addition I have also a variable named X. X can take any value. I want to find closest and smaller 'Key' value to X. I can take only closest value via this code block. But, it can't take smaller one.

var diffs = kaynaklarArray[l].blanks.SelectMany((item, index) => item.Select(entry => new { Index = index, Key = entry.Key, Diff = Math.Abs(entry.Key - X) })).OrderBy(item => item.Diff);
var closestDiff = diffs.First();
var key = closestDiff.Key;
var value = (kaynaklarArray[l].blanks[closestDiff.Index])[closestDiff.Key];

如果X是1000,我想取空白索引:1和键:750,因为它是SMALLER than X但是这个代码块的索引是:2和Key:1200.我不想要它。

if X is 1000, I want to take blanks index: 1 and Key: 750, because it is SMALLER than X. However this code block takes index:2 and Key: 1200. I don't want it.

我该怎么做?

另外我还有一个这样的列表:

In addition I've also 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).

再次,我有代码块为此。但它不能采取较小的一个。它最接近一个。

Again, I have code block for this. But it can't take smaller one. It takes closest one.

var diffSecond = lastList.SelectMany((listS, listIndex) => listS.
SelectMany((array, arrayIndex) => array.Select((item, itemIndex) => new
{
    ListIndex = listIndex,
    ArrayIndex = arrayIndex,
    ItemIndex = itemIndex,
    Diff = Math.Abs(item - X)
})));

var closestDiffS = diffSecond.Aggregate((agg, item) => (item.Diff < agg.Diff) ? item : agg);                                            


推荐答案

更改

Diff = Math.Abs(item - X)

Diff = X - item

然后

var closestDiffS = diffSecond.Aggregate((agg, item) => (item.Diff > 0 && item.Diff < agg.Diff) ? item : agg);

或者,您需要一个Where。我认为应该去这里:

Or, you need a Where. I think it's supposed to go here:

var diffSecond = lastList.SelectMany((listS, listIndex) => listS.
SelectMany((array, arrayIndex) => array //Not here, 'cause you need the index
.Select((item, itemIndex) => new
{
    ListIndex = listIndex,
    ArrayIndex = arrayIndex,
    ItemIndex = itemIndex,
    Diff = X - item
}).Where(item => item.Diff > 0)
));

要获取最小的差异的所有列表:

To get all the lists with the smallest Diff:

var closestDiffS = diffSecond.GroupBy(item => item.Diff).OrderBy(group => group.Key).FirstOrDefault();

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆