0

我有一个 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();
4

3 回答 3

4

您可以使用(or ) 的重载,SelectWhere它也投影元素的索引:

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();

旁注:考虑将变量名称更改为更有意义。那是不可读的。

于 2013-09-04T08:50:38.520 回答
1

你是这个意思吗?

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();
于 2013-09-04T08:51:30.840 回答
0

另请注意,如果您想经常搜索与谓词匹配的项目的索引,则可能值得编写一个非常简单的扩展方法:

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));
于 2013-09-04T09:08:16.733 回答