根据某些条件获取List <long>中的某个元素范围

时间:2015-11-23 03:11:29

标签: list search c#-4.0

  • 我有2个List<long>valueCovvalueWat),数据类型为long
  • 当找不到某个列表元素时,我需要获取下一个 更接近于搜索价值最少的元素。

为此:

  • 我正在迭代valueWat的元素(x),如果没有确切的话 在valueCov中匹配它,然后进入我需要找到的其他部分 非常接近“x”的元素。

  • 我需要一种从中找到最接近的下一个元素的解决方案/方法 List

代码段:

foreach (var y in sortedCov){
                    valueCov.Add(y.Value);
                }
                //Console.WriteLine("initial" + valueCov.Count);
                foreach (var x in valueWat){
                    //foreach (var y in valueCov){
                       // var keys = new List<long>(y.Value);
                            int index = valueCov.BinarySearch(x);
                            int lower;
                            int upper;
                                if (index >= 0) {
                                  lower = upper = index;
                                  blockedWaterCoverMap.Add(x, valueCov[index]);
                                  valueCov.RemoveAt(index);
                                                }
                                else  {
                                    //foreach (var y in valueCov){
                                        //subListCov = valueCov.FindAll((y < x + 7) && (y > x - 7));
                                       // }

                                      }

1 个答案:

答案 0 :(得分:2)

如果我理解正确你想要这样的功能:

int FindClosest(long data) {
        int i = 0; // index of currently checked element from valueCov
        int index = i; // returned index of the closest element 
        // here is current lowest distance to searched value:
        long min = long.MaxValue; 
        // currently counted difference between input value
        // and the next element of the list valueCov
        long diff = 0; 
        foreach (var elem in valueCov) {
            if ((diff = Math.Abs(elem - data)) <= min) {
                min = diff;
                index = i; // the searched index is updated
            }
            i++; 
        }

        // random selection of the index from the closest
        // found values
        List<int> indices = new List<int>();
        for (int n = 0; n < valueCov.Length; n++) {
             if (valueCov[n] == valueCov[index])
                indices.Add(n);
        }
        Random r = new Random();
        index = indices[r.Next(indices.Count)];
        return index;
}

希望它有所帮助。