Reputation: 10738
In the following code I'm checking if a certain item exists in an ObservableCollection
and if it does, I want to grab its index so I can move that item to the top but I cannot figure it out.
My object:
public class RecentFile
{
public string FileName { get; set; }
public string DateAdded { get; set; }
}
Cod for finding index of item:
if (recentFilesObservableCollection.Any(f => f.FileName == "MyFileName")) {
foreach (RecentFile file in recentFilesObservableCollection) {
if (file.FileName == "MyFileName") {
var x = RecentFilesDataGrid[(recentFilesObservableCollection.IndexOf(file)];
}
}
}
What would be the best way to get the index number if the item exists?
Ultimately what I need to do is...
Upvotes: 1
Views: 4150
Reputation: 4552
You can create extension methods similar to List<T>.FindIndex(...)
methods:
public static class ObservableCollectionExtensions
{
public static int FindIndex<T>(this ObservableCollection<T> ts, Predicate<T> match)
{
return ts.FindIndex(0, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, Predicate<T> match)
{
return ts.FindIndex(startIndex, ts.Count, match);
}
public static int FindIndex<T>(this ObservableCollection<T> ts, int startIndex, int count, Predicate<T> match)
{
if (startIndex < 0) startIndex = 0;
if (count > ts.Count) count = ts.Count;
for (int i = startIndex; i < count; i++)
{
if (match(ts[i])) return i;
}
return -1;
}
}
Usage:
int index = recentFilesObservableCollection.FindIndex(f => f.FileName == "MyFileName");
if (index > 0)
{
// Move it to the top of the list
recentFilesObservableCollection.Move(index, 0);
}
Upvotes: 0
Reputation: 123
Try this: Int index=YourCollection.IndexOf(x => x.fileName == “name”); And then use MoveItem which takes current index and destination index.
Upvotes: 0
Reputation: 247153
Check if item exists. If it does get the item to find its index. From there move it.
//Check if item exists
if (recentFilesObservableCollection.Any(f => f.FileName == "MyFileName")) {
//If it does, get item
var file = recentFilesObservableCollection.First(f => f.FileName == "MyFileName");
//grab its index
var index = recentFilesObservableCollection.IndexOf(file);
if (index > 0)
//move it to the top of the list
recentFilesObservableCollection.Move(index, 0);
}
Another alternative that achieves the same result with less enumerations.
var item = recentFilesObservableCollection
.Select((file, index) => new { file, index })
.FirstOrDefault(f => f.file.FileName == "MyFileName"));
if(item != null && item.index > 0) // or if(item?.index > 0)
recentFilesObservableCollection.Move(item.index, 0);
Upvotes: 4