Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Item in ObservableCollection without using a loop

Currently i have the following syntax (list is a list containing objects with many different properties (where Title is one of them):

for (int i=0; i < list.Count; i++) {    if(title == list[i].Title)    {     //do something    } } 

How can i access the list[i].Title without having to loop over my entire collection? Since my list tends to grow large this can impact the performance of my program.

I am having a lot of similar syntax across my program (accessing public properties trough a for loop and by index). But im a sure there must be a better and elegant way of doing this?

The find method does seem to be a option since my list contains objects.

like image 938
PeterP Avatar asked May 08 '12 12:05

PeterP


People also ask

How do I cast ObservableCollection to list?

Given that ObservableCollection<T> implements IEnumerable<T> you can give it to the constructor of List<T> : List<T> myList = new List<T>(myObservableCollection); Where T is the type of the items in the collection.


2 Answers

I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.

May be you mean using a LINQ, like for example:

list.Where(x=>x.Title == title) 

It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.

Hope this helps.

EDIT

In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.

like image 178
Tigran Avatar answered Sep 23 '22 11:09

Tigran


Here comes Linq:

var listItem = list.Single(i => i.Title == title); 

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title); 
like image 34
Patryk Ćwiek Avatar answered Sep 23 '22 11:09

Patryk Ćwiek