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

时间:2014-09-18 10:34:12

标签: c# linq dictionary indexing

我有一个这样的清单:

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

保留一些索引值:

enter image description here

另外我还有一个名为X的变量.X可以取任何值。我想找到最接近X的“Key”值。例如:

如果X是1300,我想采用空白索引:2和密钥:1200。 我怎么能通过linq这样做?或者,还有其他解决方案吗?

提前致谢。

编辑:如果它不是字典怎么办?如果是这样的列表怎么办:

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

enter image description here

这一次,我想先获取List的索引和第二个List的索引。例如,如果X是800,我想取0和0(索引0)并且取1和1(索引1)我该怎么做?

2 个答案:

答案 0 :(得分:3)

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中,您将找到关闭项的索引(列表索引,数组索引和数组项索引)

答案 1 :(得分:0)

这可能不是最优化的方式,但它应该可行,

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