日期:2014-05-20  浏览次数:21389 次

使用LINQ查询集合中符合条件序列的序号
使用LINQ进行简单的查询很好操作。
但俺需要查询符合条件者在集合中的序号,不知如何实现。
比如有这么个数组 NNN = Int[4]{11,22,33,44}
var ABCD = from Aaa in NNN where Aaa=22 select Aaa.
能找到满足条件的成员,但我需要的是序号“1”。
请教高人

------解决方案--------------------
C# code

  int[] NNN = { 11, 22, 33, 44 };
  int sort = NNN.Select((s, index) => new { s, index }).FirstOrDefault(w => w.s == 22).index;
  int sort1 = NNN.ToList().IndexOf(22);

------解决方案--------------------
C# code

void Main()
{
            var NNN = new int[4] { 11, 22, 33, 44 };
         
            var newNNN = NNN.ToDictionary(m => m, n1 => NNN.Select((a, index) => new { a, index }).FirstOrDefault(b =>b.a== n1).index);
 

            Console.WriteLine(newNNN[22]); //1
}

------解决方案--------------------
C# code
            int[] NNN = { 11, 22, 33, 44 };
            var query = NNN.Where(n => n == 22).Select((n, i) => new { n = n, i = i+1 });

            query.ToList().ForEach(q => Console.WriteLine("n={0}      i={1}", q.n, q.i));

------解决方案--------------------
第一个问题,用Array.IndexOf,远简洁于Linq
C# code
int[] aa = {1,2,3,4,5};
int index = Array.IndexOf(aa, 1);