A neat way to set the position of my object in linq collections

I currently have an object called Week. Week is part of the Season object. the season may contain many weeks. What I want to do is find the position of my week (this is the first week of the season (like # 1), or this is the second (like # 2).

int i = 0;
        foreach ( var w in Season.Weeks.OrderBy(w => w.WeekStarts)){
            if(w.Id == Id){
                return i;
            }
            i+=1;
        }

At the moment, this is what I have. I order weeks in a second to start them, to make sure they are in the correct order. and I scroll through them until I find a week that matches the week in which I am watching. and return the int I am counting.

I feel that there should be an easier linq way to do this, as it feels pretty dirty!

+3
source share
3 answers

FindIndex /, Select, :

 return Season.Weeks
              .OrderBy(w => w.WeekStarts)
              .Select((week, index) => new { Week = week, Index = index })
              .First(a => a.Week.Id == Id)
              .Index;

, Id , FirstOrDefault :

var weekIndexTuple = Season.Weeks
                           .OrderBy(w => w.WeekStarts)
                           .Select((week, index) => 
                                    new { Week = week, Index = index })
                           .FirstOrDefault(a => a.Week.Id == Id);

if(weekIndexTuple != null)
{
    return weekIndexTuple.Index;
}
else
{
   // I'm not sure how you want to continue in this case.
   ...      
}
+5

: IEnumerable?

, . . :

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}
+2

SLaks has published a neat extension method for IEnumerable, which gives you a method for finding an index from LINQ calls themselves: How do I get an index using LINQ?

+1
source

Source: https://habr.com/ru/post/1792933/


All Articles