获取与我的 linq 匹配的行的索引
本文关键字:索引 我的 linq 获取 | 更新日期: 2023-09-27 18:30:16
>我有一个linq语句,我想知道是否有可能获得与我的语句匹配的行指示?在这里:
var result = list3.Where(middle => list4.Any(x => x == middle.Middle.category1)).Select(obj => new { obj, dt = DateTime.ParseExact(obj.LeftColumn, dateFormat, CultureInfo.InvariantCulture) })
.Where(x => x.dt >= datetimepickerChoice1 && x.dt <= datetimepickerChoice2)
.Select(x => x.obj).ToList();
您可以使用 Select
(或 Where
)的重载,它也投影元素的索引:
var result = list3.Select((middle, index) => new{ middle, index })
.Where(x => list4.Any(xx => xx == x.middle.Middle.category1))
.Select(x => new { x.middle, x.index, dt = DateTime.ParseExact(x.middle.LeftColumn, dateFormat, CultureInfo.InvariantCulture) })
.Where(x => x.dt >= czas11 && x.dt <= czas22)
.Select(x => x.index)
.ToList();
旁注:考虑更改变量名称以使其更有意义。这是不可读的。
你的意思是这个吗?
var result = list3.Where(middle => list4.Any(x => x == middle.Middle.category1))
.Select(obj => new { obj, dt = DateTime.ParseExact(obj.LeftColumn, dateFormat, CultureInfo.InvariantCulture) })
.Where(x => x.dt >= czas11 && x.dt <= czas22)
.Select((x,index) =>new{ x.obj,Index=index}).ToList();
另请注意,如果您想经常搜索与谓词匹配的项目的指示,则可能值得编写一个非常简单的扩展方法:
public static class IEnumerableExt
{
public static IEnumerable<int> FindIndices<T>(this IEnumerable<T> self, Predicate<T> predicate)
{
int i = 0;
foreach (var element in self)
{
if (predicate(element))
yield return i;
++i;
}
}
}
你会这样称呼:
var result = list3.FindIndices(x => list4.Any(xx => xx == x.middle.Middle.category1));