如何获取列表中包含的项目数组

问题描述

我必须使用 lambda 查找通过 List 中的参数数组的名称。我是否必须迭代以从数组中搜索相同的名称

 partial class StudentTestscoresProgram
    {
        static public List<Student> GetStudents()
        {
            List<Student> students = new List<Student>
            {
                new Student { Name = "Michael",scores = new int[] { 94,92,91,91 } },new Student { Name = "Isabelle",scores = new int[] { 66,87,65,93,86} },new Student { Name = "Chastity",scores = new int[] { 76,61,73,66,54} },new Student { Name = "Chaim",55,82,62,52} },new Student { Name = "Patience",scores = new int[] { 91,79,58,63,55} },new Student { Name = "Echo",scores = new int[] { 74,85,75,new Student { Name = "Pamela",scores = new int[] { 73,64,53,72,68} },new Student { Name = "Anne",scores = new int[] { 78,96,52,60} },new Student { Name = "Bruno",scores = new int[] { 62,70,74} },new Student { Name = "Tanya",scores = new int[] { 60,77,88,99,40} }

 };

            return students;
        }

  /// <summary>
        /// Find a set of students and display their information
        /// 
        /// You MUST use lambda or Predicate/delegate with FindAll for this.
        /// </summary>
        /// <param name="students">list of students</param>
        /// <param name="search">array of student names to find</param>
        static void FindStudents(List<Student> students,params string[] search)
        {
            //I have to fill the code in here. 
            List<Student> subArray = students.FindAll(i => i.Name == search[]); //This is what I was thinking of
        }

我要填码,怎么搜索数组?

程序是

 static void Main(string[] args)
        {
            List<Student> students = GetStudents();
            FindStudents(students,"Bruno","Tanya","Tony","Sami");
            FindStudents(students,"Xerxes");
        }

输出应该是这样的

Searching for the following students:
Bruno
Tanya
Tony
Sami
Found the following students:
Name: Bruno,scores: 62,82
Name: Tanya,scores: 60,99
Searching for the following students:
Xerxes
Found the following students:

解决方法

我只会关注实际的Lambda。匹配准确的输出结果由您决定

但是,您可以只使用 Contains

确定序列是否包含指定元素。

static List<Student> FindStudents(List<Student> students,params string[] search)
    => students.FindAll(i => search.Contains(i.Name));

或者,如果您想要快速不区分大小写的搜索,您可以使用 HashSetStringComparer

static void FindStudents(List<Student> students,params string[] search)
{
    var hash = search.ToHashSet(StringComparer.InvariantCultureIgnoreCase);
    return students.FindAll(i => hash.Contains(i.Name));
}

示例

var students = GetStudents();
var results = FindStudents(students,"Pamela","Anne","Tony","Sami");

foreach (var result in results)
   Console.WriteLine($"{result.Name} : {string.Join(",",result.Scores)}");

输出

Pamela : 73,64,53,72,68
Anne : 78,96,52,79,60

注意:这些方法缺乏合适的输入检查