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

Time:03-26

I'm trying to execute method "UpdateConnection" against a qualified element in a list. I didn't see "Where" or "Select" as avaliable extension methods. Is there a cleaner way to filter on this list other than "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);

CodePudding user response:

I would use FirstOrDefault extension method which might let your code clear from System.Linq namespace.

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