开发者

C# Passing value of a list element to update local variable

I have a few local variables and I want to divide them all divide them all by the same number.

decimal a = 0;
decimal b = 0;
decimal c = 0; 
...
decimal n = 0;
decimal divisor = 0;

<perform calculations to give all variables meaningful values>

divide each decimal (a - n) by divisor then assign value

Beside dividing and assigning 开发者_运维百科every variable with:

a = a / divisor;
b = b / divisor;
and so on...

Is there a faster way? I'm thinking something along the lines of putting them all in a collection and iterating over it...

I don't need the values in a list, I need the variables to contain them. I was thinking of something along the lines using a list of pointers, iterating over it and setting the values that way.


Absolutely - use an array (decimal[]) or a List<decimal> then:

for (int i = 0; i < list.Count; i++)
{
    list[i] /= divisor;
}

Alternatively, you could go for a more functional approach, which LINQ makes particularly easy:

IEnumerable<decimal> divided = list.Select(x => x / divisor);

You can build a new array or list from that IEnumerable<decimal> using the ToArray or ToList methods respectively. For example, you could write:

list = list.Select(x => x / divisor).ToList();

Be aware that this isn't the same as the first code though - it makes the list variable refer to a new list containing the divided numbers; if anything else has a reference to the original list, it won't see any changes.


If you have them in a collection, you can do something like that:

var myCollection = // setup the collection;

var newCollection = from i in myCollection
                    select i / divisor;

That will give you a new collection with all of the original elements divided by your "divisor" variable.


"Be aware that this isn't the same as the first code though - it makes the list variable refer to a new list containing the divided numbers; if anything else has a reference to the original list, it won't see any changes." - J Skeet

Per the question - "I don't need the values in a list, I need the variables to contain them. I was thinking of something along the lines using a list of pointers, iterating over it and setting the values that way."

This is not possible and as Mr. Copsey pointed out - "You're better off working with the list of values, as Jon suggested. Trying to make a list of pointers to the original values, iterate over them, etc, will be more work than just setting them directly (plus much less maintainable)."


var result = new List<decimal>(14) {a, b, c, d, e, f, g, h, i, j, k, l, m, n}
                   .ForEach(x => x /= divisor};

Of course, this won't actually adjust the variables a, b, c ... n.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜