1

I have two list ,list1 of size 5 elements and list2 of size 6 elements. I want to iterate for larger list size(eg. 6 in this case) using foreach statement but the problem is I am not using if condition to check which list is larger . So how can I do the necessary task.

if (list1.Count>list2.Count) // here I donot want to use if statement
{                            // do it in 1 statement only
    Size=list1.Count;
    foreach (var item in list1)
    {
        // do something
    }
}
else 
{
    Size = list2.Count;
    foreach (var item in list2)
    {
        // do something
    }
}
pt12lol
  • 2,332
  • 1
  • 22
  • 48
raunak
  • 29
  • 1
  • 11
  • What is issue with `if-condition`? – Hassan May 28 '14 at 11:22
  • First of all there are many lists in my requirement and it is looking complicated too – raunak May 28 '14 at 11:24
  • If a simple comparison in an `if` statement looks complicated to you, I'm not sure programming is for you. – Rik May 28 '14 at 11:28
  • @Rik how will i use 'if' statement if there are 5 different list and will do the same task ,Thank you:p – raunak May 28 '14 at 11:31
  • @user1909259 you want to know which list size is greater out of many lists. And then you want to run foreach on the larger one only? – Hassan May 28 '14 at 11:39
  • @user1909259 Aha, now we're getting to the root of the problem. See my updated answer below. – Rik May 28 '14 at 11:43

2 Answers2

6

You can move the condition into the foreach:

foreach(var item in (list1.Count > list2.Count ? list1 : list2))
{
    // do stuff
}

If you have several Lists (more than 2), you can create collection and get the maximum using LINQ:

var myLists = new List<List<T>>(); // T is the generic type of your Lists, obviously
myLists.Add(list1);
myLists.Add(list2);
...
myLists.Add(listN);

// iterate over the largest one:
foreach (var item in myLists.First(l => l.Count == lists.Max(x=>x.Count)))
{
    // do stuff
}
Rik
  • 28,507
  • 14
  • 48
  • 67
4
var list = list1.Count > list2.Count ? list1 : list2;

foreach(var item in  list)
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Even though Rik's answer would also work, I like this solution better since it's more readable – user3036342 May 28 '14 at 11:20
  • I agree this is more readable then my answer, but OP specified "do it in 1 statement only". In your case, I would suggest renaming `list` to "largerList` or something for even more clarity. – Rik May 28 '14 at 11:33
  • Thank you guys I have found the solution on [link](http://stackoverflow.com/questions/1955766/iterate-two-lists-or-arrays-with-one-foreach-statement-in-c-sharp), sorry to bother you.:p – raunak May 28 '14 at 11:48