Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq expression to set all values of an array to a given value

Tags:

c#

lambda

linq

I have a bit of code that i'd like to turn into a linq expression (preferably with lambdas) to make it easier to use as a delegate. The code looks like this:

List<DateTime[]> changes = new List<DateTime[]>();
changes = PopulateChanges();
for (int i = 0; i < changes.Count; i++)
{
    for(int j = 0; j < changes[i].Length; j++)
    {
        changes[i][j] = DateTime.MinValue;
    }
}

For the life of me, I can't seem to figure this one out. I've tried using ForEach and various forms of select, etc.. nothing seems to work right.

FYI, I know that DateTime defaults to MinValue, in reality this is clearing the arrays to default after they've already been set.

Can anyone help me with a working expression?

EDIT:

I guess what I'm really saying here is I want a concise way to set all elements of a multi-dimensional array to a given value. Certainly, the nested for loop works, and I can certainly place it in a function (which I have already done). I just want something more concise that can be used more easily in a delegate without creating a multi-line monster.

like image 415
Erik Funkenbusch Avatar asked Sep 11 '09 20:09

Erik Funkenbusch


1 Answers

This should do the trick.

It's not LINQ, and it's not really much different to your nested for loops, just slightly less verbose.

changes.ForEach(x => Array.Clear(x, 0, x.Length));

There are certainly ways to (ab)use LINQ to achieve the same results, but I'd consider them to be dirty hacks. Besides, the LINQ equivalent probably wouldn't be any less verbose than my example above.

like image 67
LukeH Avatar answered Oct 23 '22 12:10

LukeH