Reputation: 858
I'm trying to find a neat way to find all of the values in an observable collection which meet a certain criteria. For this example to keep things simple lets say its the collection contains ints and I'm trying to find all of the items that are greater than 5.
The best way I currently know of doing it is like this
ObservableCollection<Int> findAllGreaterThanFive (ObservableCollection<Int> numbers)
{
ObservableCollection<Int> numbersGreaterThanFive;
foreach(Int number in numbers)
{
if (number > 5)
{
numbersGreaterThanFive.add(number);
}
}
return numbersGreaterThanFive;
}
Obviously ignore any simple solutions that take advantage to the fact I'm looking for ints I need a solution that works with any an ObservableCollection of any type with any condition. I was just wondering if checking every item with the foreach loop and the conditional is the best way of doing it?
Upvotes: 3
Views: 13277
Reputation: 516
you can use System.Linq namespace, add using statement using System.Linq
and after that you can use following Where
method.
ObservableCollection<int> list = new ObservableCollection<int>();
list.Where(i => i > 5).ToList();
you can use any kind of objects like :
ObservableCollection<DataItem> list = new ObservableCollection<DataItem>();
list.Where(i => i.ID > 10);
The code above returns DataItem's with ID greater than 10.
If you sure about there's only one record satisfying condition, you can use First()
method like :
ObservableCollection<DataItem> list = new ObservableCollection<DataItem>();
list.First(i => i.ID == 10);
Above code returns the DataItem with ID 10. But if there's no record with ID = 10 then it will throw an exception. Avoid of this if you're not sure there's only one record satisfies the condition. Also you can use FirstOrDefault()
method.
ObservableCollection<DataItem> list = new ObservableCollection<DataItem>();
DataItem item = list.FirstOrDefault(i => i.ID == 10);
if(item != null)
{
//DoWork
}
If there's no record with ID = 10, then item will be null.
Upvotes: 7
Reputation: 15367
You can say something like:
var numbersGreaterThanFive = numbers.Where(x => x > 5);
Upvotes: 9