如何使用LINQ基于每个数组的第一个索引在数字数组列表中搜索数字?

时间:2013-10-03 03:37:26

标签: c# linq

我有一个数组数组列表。我正在搜索我的搜索号落在索引0中的数字之间的两个数组。然后从第二个数组返回索引1中的数字。 (假设索引0中的数字已经排序且没有重复)

我对LINQPad的错误解决方案:

'找到'的价值应该是3因为9落在4&第二和第三阵列中的10个。然后我取第二个找到的数组并返回3,该数组位于该数组的索引1中。

List<int[]> list = new List<int[]> { new[] { 1, 5 }, new[] { 4, 6 }, new[] { 10, 3} , new[] { 15, 8} };
int searchFor = 9;
int found = list.Where(n => searchFor >= n[0] && searchFor <= n[0]).Select(i => i[1]).FirstOrDefault();
found.Dump(); //should be 3 instead of 0.

4 个答案:

答案 0 :(得分:1)

试试这个:

int found = list.Zip(list.Skip(1), (x, y) => x[0]<=searchFor&&y[0]>=searchFor?y[1]:0).FirstOrDefault(o=>o!=0);

答案 1 :(得分:1)

我的逻辑有点不同,但得到你想要的结果。如果你正在做像这样的密钥对值,我建议你只使用一个字典。在我看来,它使事情更简单,如果你没有重复键,这应该工作正常。

 // Use dictionary instead of array's if just using two int values
 var dic = new Dictionary<int, int>();
 dic.Add(1, 5);
 dic.Add(4, 6);
 dic.Add(10, 3);
 dic.Add(15, 8);

 int searchFor = 9;

 // Don't need to find this really
 int low = (from l in dic
           where l.Key <= searchFor
           select l.Key).Max();

 // Just need this       
 int found = (from h in dic
             where h.Key >= searchFor
             select h.Value).Min();


 Console.WriteLine("Low: " + low);
 Console.WriteLine("Found: " + found);

答案 2 :(得分:1)

怎么样

        var found = list.First(l => l[0] > searchFor)[1];

我应该这样做,因为我可以假设每个第一个元素都排序list

如果没有,那么

        var found = list.Orderby(l=>l[0]).First(l => l[0] > searchFor)[1];

也应该有用。

答案 3 :(得分:0)

where语句中的表达式过滤了第一个元素小于或等于且大于等于的数组。因为它不能少于同时它实际上过滤了所有具有9作为第一个元素的数组。 对于给定的数据,这导致空序列。因此,FirstOrDefault返回默认值(整数为0)。

您实际上必须查找大于或等于9的第一个元素:

int[] result = list.FirstOrDefault(arr => arr[0] >= searchFor);

if (result == null)
{
    Console.WriteLine("Not found!");
}
else
{
    Console.WriteLine(result[1]);
}