none
How to find list index using where RRS feed

  • Question

  •             List<Person> Persons = new List<Person>();
                Persons.Add(new Person() { Name = "Carlos Gonzalez", CityID = 0 });
                Persons.Add(new Person() { Name = "Mario Pontes", CityID = 5 });
                Persons.Add(new Person() { Name = "Horst Kloss", CityID = 2 });
                Persons.Add(new Person() { Name = "Martin Sommer", CityID = 3 });
                Persons.Add(new Person() { Name = "Diego Roel", CityID = 3 });
                Persons.Add(new Person() { Name = "Catherine Dewey", CityID = 4 });
                Persons.Add(new Person() { Name = "Pascale Cartrain", CityID = 4 });
                Persons.Add(new Person() { Name = "Pascale Bomar", CityID = 4 });
                Persons.Add(new Person() { Name = "Bernardo Batista", CityID = 1 });
    
                int index = Persons.FindIndex(a => a.Name.Contains("Pascale"));
    
    
                //Person agedTwenty = Persons.Where<Person>(a => a.Name.Contains("Pascale")).Single<Person>();
                Person agedTwenty = Persons.Where(a => a.Name.Contains("Bomar") && a.CityID==1).FirstOrDefault();
                int index1 = Persons.IndexOf(agedTwenty);
    
    i have done the code above way....is it correct?
    Saturday, March 16, 2019 7:32 PM

Answers

  • You don't need to use Linq.

    int index = Persons.FindIndex( a => a.Name.Contains("Bomar") && a.CityID==1);

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=netframework-4.7.2

    • Marked as answer by Sudip_inn Monday, March 18, 2019 7:52 AM
    Sunday, March 17, 2019 7:50 AM

All replies

  • If the result is correct in the code than it's correct, if it does not work then provide details.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, March 16, 2019 9:41 PM
    Moderator
  • You don't need to use Linq.

    int index = Persons.FindIndex( a => a.Name.Contains("Bomar") && a.CityID==1);

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=netframework-4.7.2

    • Marked as answer by Sudip_inn Monday, March 18, 2019 7:52 AM
    Sunday, March 17, 2019 7:50 AM