Find Item in Observablecollection Without Using a Loop

Find Item in ObservableCollection without using a loop

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.

How to return all items in an ObservableCollection which satisfy a condition C#

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.

How to search an item and get its index in Observable Collection

Use LINQ :-)

var q =  PLUList.Where(X => X.ID == 13).FirstOrDefault();
if(q != null)
{
// do stuff
}
else
{
// do other stuff
}

Use this, if you want to keep it a struct:

var q =  PLUList.IndexOf( PLUList.Where(X => X.ID == 13).FirstOrDefault() );
if(q > -1)
{
// do stuff
}
else
{
// do other stuff
}

Searching specific item in ObservableCollection

Attempt no 1 should work fine, as long as the target string has the same casing (UPPERCASE vs lowercase). This search is case sensitive meaning it will NOT find "On", "oN" or "ON" bacause they have different casings. To make case insensitive search, you can use IndexOf instead, which takes a StringComparison parameter:

var asd2 = App.MainViewModel.Messages.Where(a => a.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) >= 0);

Attempt no 2 finds the start position of the first string which matches "on" (again - case sensitive)... This doesn't make any sense really, since any string which exactly matches "on", will always start a position 0.

Attempt no 3 does the same as attempt no 1, but converts the result to a list (Where returns IEnumerable)

Attempt no 4 essentially tries to find the starting position of either "true" or "false". The Contains method will return true if the string "on" (again only exact match) is found, and that result is converted to a string and passed to the IndexOf.

UPDATE

Where returns an IEnumerable (with all the matches found). If you only need to check if "on" exists, you can use Any:

bool containsOn = App.MainViewModel.Messages.Any(a => a.IndexOf("on", StringComparison.CurrentCultureIgnoreCase) >= 0);

How to Select Items in an Observable Collection with a property that matches a criteria

If you use as ObservableCollection<Hymn> but the source collection (in your case an IEnumerable<Hymn>) is not an ObservableColletion<Hymn> the cast will result in null. Documentation of Where(...) extension)

Therefore you have to create a new ObservableCollection with this IEnumerable<Hymn> as source (in constructor).

// Filter the collection by contained keywords
var filteredList = Hymns?.Where(h => h.HymnTypeName.ToLower().Contains(keyword));
if(filteredList == null)
{
// if Hymns is null or the filtered collection is null
// return an empty list
Hymns = new ObservableCollection<Hymn>();
}
// create a new ObservableCollection with the filtered list
Hymns = new ObservableCollection<Hymn>(filteredList);

Here is a working Example

C# For-Loop not adding Items to Observable Collection

You are not handling the case where neighborAliveCounter == 2 here. This is the reason why you're getting incorrect counts. The block of code below only checks for less than 2, equal to 3 and greater than 3.

//decides if to put cell alive or dead
if (neighborAliveCounter < 2 || neighborAliveCounter > 3)
{
tempCollection.Add(new CellModel() { Row = CellCollection[i].Row, Column = CellCollection[i].Column, CellBackgroundColor = new SolidColorBrush(Colors.Transparent), IsAlive = false });
}

if (neighborAliveCounter == 3)
{
tempCollection.Add(new CellModel() { Row = CellCollection[i].Row, Column = CellCollection[i].Column, CellBackgroundColor = new SolidColorBrush(Colors.LightSeaGreen), IsAlive = true });
}

Is there a way to get a range from an ObservableCollection?

You can use Skip and Take.

System.Collections.ObjectModel.ObservableCollection<int> coll = 
new System.Collections.ObjectModel.ObservableCollection<int>()
{ 1, 2, 3, 4, 5 };
foreach (var i in coll.Skip(2).Take(2))
{
Console.WriteLine(i);
}


Related Topics



Leave a reply



Submit