Find closest and smaller value in a list in C# with linq?

守給你的承諾、 提交于 2020-02-05 10:07:21

问题


I've a list like this:

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

This keep some index values:

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];

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.

How can I do this?

In addition I've also a List like this:

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

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);                                            

回答1:


Change

Diff = Math.Abs(item - X)

to

Diff = X - item

and then

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

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();


来源:https://stackoverflow.com/questions/26037534/find-closest-and-smaller-value-in-a-list-in-c-sharp-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!