0

I have a linq statement and I would like to know if it is possible to get indicies of lines that match my statement? Here it is:

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();
Michal_LFC
  • 649
  • 3
  • 11
  • 25
  • possible duplicate of [how to find the index particular items in the list using linq?](http://stackoverflow.com/questions/4374237/how-to-find-the-index-particular-items-in-the-list-using-linq) – Lasse Espeholt Sep 04 '13 at 08:50
  • At first, you should refactor and beautify your statement, because it is understandable for machine but not for programmer who's doing review of your code. – sgnsajgon Sep 04 '13 at 08:50
  • Do you want the index of the matching lines or the original index of the lines that match? – Tim Schmelter Sep 04 '13 at 08:58

3 Answers3

4

You can use the overload of Select (or Where) which projects also the index of the element:

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

Side-note: consider to change your variable names to be more meaningful. That is unreadable.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

do you mean this?

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();
Tim.Tang
  • 3,158
  • 1
  • 15
  • 18
  • This returns the index of the matching lines, so if 3 lines out of 100 match the indices start from 0 and end with 2. I doubt that this is what OP wants. I assume(I may be wrong) that he needs the original index. – Tim Schmelter Sep 04 '13 at 08:56
0

Also note that if you want to search for the indicies of items matching a predicate very often, it could be worth writing a very simple extension method:

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;
        }
    }
}

Which you would call like this:

var result = list3.FindIndices(x => list4.Any(xx => xx == x.middle.Middle.category1));
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276