在Linq中从Select查询中查找索引

本文关键字:查找 索引 查询 Select Linq 中从 | 更新日期: 2023-09-27 18:18:02

我试图找到List<>中两个属性之间的差异是maxindex ?目前,我正在使用下面的LINQ查询找到max:

var result = link.Select(x => Math.Abs(x.Prop1 - x.Prop2)).Max();

如何获取索引

在Linq中从Select查询中查找索引

var result = 
     link.Select((x, i) => new { value = Math.Abs(x.Prop1 - x.Prop2), index = i })
          .OrderByDescending(x=>x.value)
          .FirstOrDefault();
var indexValue = result?.index;
var maxValue = result?.value;

如果您有大量的数据,您可能会担心这些方法在获得结果之前创建了2个额外的数据集。您可以使用from语句并只生成一个额外的集合:

int index = (from i in Enumerable.Range(0, link.Count)
             orderby Math.Abs(link.Prop1 - link.Prop2)
             select new { index = i, value = link[i] }).First().index;

或者使用普通的for循环,不创建任何额外的集合:

int max = 0;
int indx = 0;
for(int i = 0; i < link.Count;i++)
{
    int temp = Math.Abs(link.Prop1 - link.Prop2);
    if (temp > max)
    {
        max = temp;
        indx = i;
    }
}

以下是使用Max的工作版本,需要实现Icomparable<T> (代码是使用LinqPad创建的,它包含一些用于验证的测试数据)

void Main()
{
    List<Test> link = Test.FetchList();
    var result = link.Select((x, i) => new { x.Prop1, x.Prop2, index = i })
                     .Max(y => new Result {value = Math.Abs(y.Prop1 - y.Prop2), index = y.index});
    result.Dump(); // In this case result would be index 2
}
public class Test
{
    public int Prop1 { get; set;}
    public int Prop2 { get; set;}
    public static List<Test> FetchList()
    {
      var returnList = new List<Test>();
        returnList.Add(new Test { Prop1 = 1, Prop2 = -5});
        returnList.Add(new Test { Prop1 = 2, Prop2 = -5});
        returnList.Add(new Test { Prop1 = 1, Prop2 = -9});
        returnList.Add(new Test { Prop1 = 3, Prop2 = -2});
        returnList.Add(new Test { Prop1 = 21, Prop2 = 15});
      return (returnList);
    }
}
public class Result : IComparable<Result>
{
    public int value { get; set; }
    public int index { get; set; }
    public int CompareTo(Result other)
    {
       return (value - other.value);
    }
}
var r =  link
        .Select((x,idx)=>new{v = x, idx})
        .OrderBy(x=>Math.Abs(x.v.Prop2 - x.v.Prop1))
        .FirstOrDefault();
return r !=null ? r.idx : -1;