You must Sign In to post a response.
  • Category: ASP.Net MVC

    How to iterate list and apply logic after two item

    Hi experts,

    I want to iterate IList which can have any number of items and i want my result like below:

    Item Number --> logic
    1,2 --> Logic A
    3,4 --> Logic B
    5,6 --> Logic A
    7,8 --> Logic B
    9,10 --> Logic A

    here i want to change logic after every two item and apply logic A & B. Is there any way i can do this
  • #769198
    Hi Arun,

    You can iterate throgh list using foreach loop or linq.But foreach takes more time to excecute if you have large list.So I would suggest you to go with linq.

    Here the idea is to first group the elements by indexes. Dividing by 2 has the effect of grouping them into groups of 2. Then convert each group to a list and the IEnumerable of List to a List of Lists

    public static IList<IList<T>> Split<T>(IList<T> source)
    return source
    .Select((x, i) => new { Index = i, Value = x })
    .GroupBy(x => x.Index / 2)
    .Select(x => x.Select(v => v.Value).ToList())

    Then apply your logic on this sub list

    Hope it helps!


  • Sign In to post your comments