1

I've the following

        List<decimal> Prices = new List<decimal>();
        Prices.Add(999.99M);
        Prices.Add(19.99M);
        Prices.Add(2.75M);
        Prices.Add(9.99M);
        Prices.Add(2.99M);
        Prices.Add(2.99M);
        Prices.Add(99.99M);

I can use Linq to get the smallest value by

        decimal Min = Prices.Min(r => r);

But how can I set the smallest value to 0 in the current list ?

UPDATE

How can I deal with two smallest prices for example 2.99 and 2.99, I'd only want to set 1 to 0

3 Answers 3

9
        List<decimal> Prices = new List<decimal>();
        Prices.Add((decimal)999.99);
        Prices.Add((decimal)19.99);
        Prices.Add((decimal)2.75);
        Prices.Add((decimal)9.99);
        Prices.Add((decimal)2.99);
        Prices.Add((decimal)99.99);

        decimal minimum = Prices.Min();
        Prices = Prices.Select(price => price > minimum ? price : 0).ToList();

This will set ALL prices equal to minimal value to 0.

UPDATE

How can I deal with two smallest prices for example 2.99 and 2.99, I'd only want to set 1 to 0

Well, when this requirement is added to the equation, then @lazyberezovsky's (deleted for a moment, undeleted now) solution was the right one for you:

Prices[Prices.IndexOf(Prices.Min())] = 0;
Sign up to request clarification or add additional context in comments.

Comments

4
var prices = new List<decimal> {
     999.99M, 19.99M, 2.75M, 9.99M, 2.99M, 99.99M };

Prices[Prices.IndexOf(Prices.Min())] = 0;

If you want to update all min prices:

var min = Prices.Min();

for (int i = 0; i < Prices.Count; i++)
    if (Prices[i] == min)
        Prices[i] = 0;

NOTES: You don't have to pass selector into Enumerable.Min() method, you can declare decimal liters with suffix M, and you can use collection initializer to fill list of prices.

3 Comments

Yes, but more than one price may have the minimum value (that the OP wants to set to 0), and Prices.IndexOf only returns one index.
But as it turns out, your original solution was what the OP actually wanted :) Just the first minimum price. He didn't specify that requirement at first, but this is what he meant, see the updated question.
@KonradMorawski :)) You never know what OP wants
2

In LINQ you can do this (it will set all minimal prices to 0)

var min = Prices.Min();
Prices = Prices.Select(x=> x==min? 0:x).ToList();

2 Comments

Please move Prices.Min() outside the loop.
You do realize that this will have worst case performance as you will have n^2 iterations of the loop. Min prices, in max time!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.