Reputation: 361
I want to check a list for a given value and the list should contain only the given value. Say for example
List<string> alltypes = new List<string>();
i want to check 'alltypes' for something like a value 'sedan' and if that is the only element in the list alltypes then return true
Appreciate any help..thank u
Upvotes: 1
Views: 3096
Reputation: 1724
use Linq All query - will return true if all members of the list match the input query
var result = alltypes.Count > 0 && alltypes.All(a => a == "sedan")
result will be true if list only contains strings of "sedan"
Upvotes: 2
Reputation: 10804
Depends if you are saying there should be one and only one value
var result = alltypes.Length == 1 && alltypes[0] == "sedan"
or if you are saying all the values in the the list (and there may be many)
var result = alltypes.Length > 0 && alltypes.All(a => a == "sedan")
Careful with All as it will return true if the list is empty:
true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
Upvotes: 2