如果项目存在于 C#/WPF 中的 ObservableCollection 中,则查找数字的索引

fs_*_*gre 2 c#

在下面的代码中,我正在检查某个项目是否存在于 an 中ObservableCollection,如果存在,我想获取它的索引,以便我可以将该项目移动到顶部,但我无法弄清楚。

我的对象:

public class RecentFile
{
    public string FileName { get; set; }
    public string DateAdded { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

用于查找项目索引的代码:

if (recentFilesObservableCollection.Any(f => f.FileName == "MyFileName")) {

    foreach (RecentFile file in recentFilesObservableCollection) {
        if (file.FileName == "MyFileName") {
            var x = RecentFilesDataGrid[(recentFilesObservableCollection.IndexOf(file)];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果项目存在,获取索引号的最佳方法是什么?

最终我需要做的是......

  1. 检查项目是否存在
  2. 如果确实将其移至列表顶部

Nko*_*osi 5

检查项目是否存在。如果它确实让项目找到它的索引。从那里移动它。

//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);
}
Run Code Online (Sandbox Code Playgroud)

另一种使用较少枚举实现相同结果的替代方法。

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);
Run Code Online (Sandbox Code Playgroud)