Get index of lines that match my linq

前端 未结 3 1643
我寻月下人不归
我寻月下人不归 2021-01-25 21:45

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          


        
相关标签:
3条回答
  • 2021-01-25 22:23

    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));
    
    0 讨论(0)
  • 2021-01-25 22:26

    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();
    
    0 讨论(0)
  • 2021-01-25 22:40

    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.

    0 讨论(0)
提交回复
热议问题