Cómo iterar para una lista más grande usando foreach

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
    }
}

preguntado el 28 de mayo de 14 a las 12:05

What is issue with if-condition? -

First of all there are many lists in my requirement and it is looking complicated too -

If a simple comparison in an if statement looks complicated to you, I'm not sure programming is for you. -

@Rik how will i use 'if' statement if there are 5 different list and will do the same task ,Thank you:p -

@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? -

2 Respuestas

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
}

contestado el 28 de mayo de 14 a las 12:05

Sorry, I either donot want to use '> ? :' too. - raunak

@ user1909259 Luego use < and swap the List :p - Sriram Sakthivel

Why not? How else do you propose to select the bigger of the lists without comparing their sizes? - Rik

I was thinking any inbuilt standard method - raunak

LA Zip operation in that link does something completely different from what you described. - Rik

var list = list1.Count > list2.Count ? list1 : list2;

foreach(var item in  list)

contestado el 28 de mayo de 14 a las 12:05

Even though Rik's answer would also work, I like this solution better since it's more readable - user3036342

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

Thank you guys I have found the solution on aquí, sorry to bother you.:p - raunak

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.