-2

how to check if a decimal value exists in a list of decimal C#.

I want to achieve the following, but I am looking for right way to compare a decimal value from a list of decimals.

decimal value = 100;
List<decimal > Amounts = new List<decimal>() { 20, 30 };
I want to compare if 
Amounts.Any(value)
//do something
else
do something
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Jasmine
  • 5,186
  • 16
  • 62
  • 114
  • I am using if(Amounts.Contains(decimal.Parse(stringValue, NumberStyles.Currency))) – Jasmine Jan 15 '19 at 00:08
  • Please don't edit in answers to the question. If you feel the question no longer a question deleting is better choice. If you really feel that no one before you tried to find https://www.bing.com/search?q=c%23+value+in+list feel free to [edit] the question to clarify how your case is unique (so post can be re-opened) and then provide you answer as *answer* (and not an edit to the question). – Alexei Levenkov Jan 15 '19 at 00:20
  • I didnt' downvote, but you're supposed to do some research on your own before asking a question. How to search for a value in a list in c# is thoroughly covered on the internet already. – Ben Jan 15 '19 at 00:24
  • The answer duplicated is specific to Linq, This question can be answered without Linq, using List.Contains(), as @Learner has discovered. With or without Linq, .Contains() is exactly the correct approach. – glenebob Jan 15 '19 at 02:52

1 Answers1

1

You can use the .Find() method from here:

List.Find(Predicate) Method

Example:

decimal valueToFind = 100;
List<decimal> amounts = new List<decimal>() { 20, 30 };
var result = amounts.Find(x => x == valueToFind);

if (result == 0){
    //not found
}
else if (result == valueToFind){
    //found
}
troyw1636
  • 338
  • 2
  • 5
  • Hi Troy, how different is your answer to my approach? My approach of using Contains will throw exception? Comparing to the robustness of yours? – Jasmine Jan 15 '19 at 00:20
  • Yours doesnt looks redeable for me I am a layman – Jasmine Jan 15 '19 at 00:20
  • @learner "Find" will return the found item, "Contains" will return a boolean value indicating whether or not the item was found. Depending on what you're trying to achieve, "Contains" may be more useful for you. – troyw1636 Jan 15 '19 at 00:24
  • Thank you Troy, good to know it returns the actual item like Intersect. So its ismilar to intersect ist? Only thing intersect is for strings.? Good to know. – Jasmine Jan 15 '19 at 00:29
  • I gave you thumbsup and also tick your answer your intention to help me and your time. – Jasmine Jan 15 '19 at 00:30
  • Downvoting. This approach does not work. Consider the case of searching for the value `0`. The result will be `0` whether that value exists or not. – glenebob Jan 15 '19 at 02:45