How can you determine the current items position whilst looping through the collection?
I’m working through decision data, grouped by each client, but I have some business logic which depends on the “position” in the set, i.e. 1st, 2nd, 3rd, etc. in conjunction with other properties of the record, e.g. if it’s the 3rd decision about a client and their rating in the instance is A then …
var multiples = from d in context.Decision_Data
group d by d.Client_No
into c
where c.Count() > 1
select c;
foreach (var grouping in multiples)
{
foreach (var item in grouping)
{
// business logic here for processing each decision for a Client_No
// BUT depends on item position ... 1st, 2nd, etc.
}
UPDATE: I appreciate I could put a counter in and manually increment, but it feels wrong and I’d of thought there was something in .NET to handle this ??
Something like this:
Side note: you can make the implementation of your LINQ query a bit more efficient.
Count() > 1will completely enumerate each group fully, which you are likely to do in the foreach anyway. Instead you can useSkip(1).Any(), which will stop iterating the group as soon as it finds two items. Obviously this will only make a real difference for (very) large input lists.