是否有比 FindIndex 更好的扩展方法来过滤通用列表?

IS there a better extension method than FindIndex to filter on a generic list?

我正在尝试对列表中的限定元素执行方法“UpdateConnection”。我没有看到“Where”或“Select”作为可用的扩展方法。除了“FindIndex”之外,还有更简洁的方法来过滤此列表吗?

public class ExistingDbConnection
{
    public string DBName { get; set; }
    public Guid Id { get; set; }
}

var list = new List<ExistingDbConnection>();

ExistingDbConnection p = new ExistingDbConnection() { DBName = "MS100", ID = Guid.NewGuid() };
list.Add(p);
p = new ExistingDbConnection() { DBName = "DS100", ID = Guid.NewGuid() };
list.Add(p);


var index = exisingConnections.FindIndex(x => x.DBName == connection.Name);
if (index < 0) index = 0;  // if no match, use the first element
status = await UpdateConnection(exisingConnections[index].Id);

我会使用 FirstOrDefault 扩展方法,这可能会让您的代码从 System.Linq 命名空间中清除。

var item = exisingConnections.FirstOrDefault(x=> x.DBName == connection.Name) ?? exisingConnections[0];
status = await UpdateConnection(item.Id);