[c#] 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.

This question is related to c# wpf collections

The answer is


Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.


You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.


I'd suggest storing these in a Hashtable. You can then access an item in the collection using the key, it's a much more efficient lookup.

var myObjects = new Hashtable();
myObjects.Add(yourObject.Title, yourObject);
...
var myRetrievedObject = myObjects["TargetTitle"];

ObservableCollection is a list so if you don't know the element position you have to look at each element until you find the expected one.

Possible optimization If your elements are sorted use a binary search to improve performances otherwise use a Dictionary as index.


i had to use it for a condition add if you don't need the index

using System.Linq;

use

if(list.Any(x => x.Title == title){
// do something here
}

this will tell you if any variable satisfies your given condition.


Consider creating an index. A dictionary can do the trick. If you need the list semantics, subclass and keep the index as a private member...


An observablecollection can be a List

{
    BuchungsSatz item = BuchungsListe.ToList.Find(x => x.BuchungsAuftragId == DGBuchungenAuftrag.CurrentItem.Id);
}

Maybe this approach would solve the problem:

int result = obsCollection.IndexOf(title);

IndexOf(T)
Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection.

(Inherited from Collection)

https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.7.2#methods


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);

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?