Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading