简体   繁体   中英

Find class value inside a List

The user will input a Lis<People> with Name , Age and Address , ie

PeopleList.Add(new People { 
  Name    = name, 
  Age     = age, 
  Address = address 
});

After the PeopleList is done, the user can search for a Name and view the Age and Address with it.

I am having a problem on how to search within PeopleList for a specific Name .

string searchName = Console.ReadLine();

if (PeopleList.Contains(new People {
    Name = searchName
})) {
    //Display name, age, address here
} else {
    Console.WriteLine("Name not found");
}

Use Linq FirstOrDefault() to determine the first element, in case one exists.

string searchName = Console.ReadLine();
People result = PeopleList.FirstOrDefault(x => x.Name == searchName);
if (result != null)
{
    Console.WriteLine("name: {0}, age: {1}, address:{2}", result.Name, result.Age, result.Address);
}
else
{
    Console.WriteLine("Name not found");
}

You can try query the collection with a help of Linq

using System.Linq;

...

string result = PeopleList
  .Where(item => item.Name == searchName)
  .Select(found => $"Name: {found.Name}; Age: {found.Age}; Address: {found.Address}") 
  .FirstOrDefault() ?? "Name not found";

Console.Write(result);

If you want to show not the first but all items found, you can Join them:

string result = string.Join(Environment.Newline, PeopleList
  .Where(item => item.Name == searchName)
  .Select(found => $"Name: {found.Name}; Age: {found.Age}; Address: {found.Address}")
);

result = string.IsNullOrEmpty(result) 
  ? "Name not found" 
  : result;

Console.Write(result);

What's happening

The signature for Contains is public static bool Contains<TSource> (...); and it only gives you a yes/no answer. In order to display the matching object you need one of the methods that return matching objects, not just yes/no if they are found. These methods are Where , First , FirstOrDefault , Single , SingleOrDefault , and more.


Note: The class should be called Person since it represents data about a single person, not about multiple people.

Person person;
List<Person> people;

Solution

BTW. @fubo was first but I think this is more complete

var searchName = Console.ReadLine();
var results = PeopleList
    .Where(x => x.Name.Contains(searchName, StringComparison.InvariantCultureIgnoreCase))
    .ToList();
if (results.Any())
{
    foreach (var person in results)
    {
        Console.WriteLine($"Found: {person.Name}");
    }
}
else
{
    Console.WriteLine("Name not found");
}

Test

Code

class Person { public string Name { get; set; } }
public static void Main(string[] args)
{
    var PeopleList = new[] { new Person { Name = "marneee" }, new Person { Name = "Mark" } };
    while (true)
    {
        var searchName = Console.ReadLine();
        var results = PeopleList
            .Where(x => x.Name.Contains(searchName, StringComparison.InvariantCultureIgnoreCase))
            .ToList();
        if (results.Any())
        {
            foreach (var person in results)
            {
                Console.WriteLine($"Found: {person.Name}");
            }
        }
        else
        {
            Console.WriteLine("Name not found");
        }
    }
}

Output

// .NETCoreApp,Version=v3.0
mar
Found: marneee
Found: Mark
marn
Found: marneee

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM