1

I have a simple model:

Id          Name             Hot
----------- ---------------- -----------
1           Nicole           False
2           Samanta          False
3           Sabrina          False

I have that list inside a ListOf<T>

I want to change the Hot property to True on all items.

My list have thousands of girls, so I am wondering if I can do it in a different way, avoiding doing the following:

foreach(var item in girls)
{
    item.Hot = True;
}
user2779312
  • 661
  • 2
  • 9
  • 23
  • 14
    *Why* do you want to avoid that? It seems the most straightforward approach to me. (Admittedly I would have chosen a rather less objectifying example,. personally...) – Jon Skeet Jan 20 '15 at 15:04
  • There is no way of circumventing the need to change each of the items; in code, this can formulated in either way, but no sensible formulation will yield a substantial improvement over the other ones. – Codor Jan 20 '15 at 15:06

4 Answers4

4

No you can not. You need to iterate over and set the property. More sexy looking code (considering that we are talking about hot girls) may look like

girls.ForEach(g=>g.Hot = true);

Worth mentioning that this does not avoid iteration over collection, just the syntax changed.

Hope this helps.

Tigran
  • 61,654
  • 8
  • 86
  • 123
1

You could use the ForEach method on List<T> instead:

girls.ForEach(girl => girl.Hot = true);

MSDN on that method can be found here.

Corey Adler
  • 15,897
  • 18
  • 66
  • 80
  • `ForEach` isn't an extension method. It's a normal method on `List`. – Jon Skeet Jan 20 '15 at 15:07
  • Actually it is being phased out :) – Botonomous Jan 20 '15 at 15:12
  • 1
    Is it really? Do you have a link for that? – Corey Adler Jan 20 '15 at 15:13
  • This isnt an offical link, but its already removed in metro style apps. Google has a lot to stay on the topic: http://stackoverflow.com/questions/10299458/is-the-listt-foreach-method-gone Its easy to roll your own extension tho..But i can see why it was removed. Cant say if this will stick tho. A lot of devs love that method in linq. – Botonomous Jan 20 '15 at 15:16
0

You could try using the select statement evaluated by ToList() due to lazy evaluation

girls.Select(g => {g.Hot = True; return g;}).ToList();
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 4
    @Codor: Well, it's a really inefficient way of doing it - but it *does* modify all the objects referred to by the existing list. – Jon Skeet Jan 20 '15 at 15:08
0

Here you go "the different way":

for(int i = 0; i < girls.Count; i++)
{
    girls[i].Hot = True;
}

or

int i = 0;
while(i < girls.Count)
{
    girls[i].Hot = True;
    i++;
}
Renatas M.
  • 11,694
  • 1
  • 43
  • 62