如何使用linq检查一个条件中的多个列表值?

0x6upsns  于 2022-12-06  发布在  其他
关注(0)|答案(3)|浏览(133)

我可以用下面的两个条件进行检查,但是在性能方面,有没有更好的方法?我希望当list中包含StudentName为John和Ram的记录时,返回true。如果只有John,则需要返回false

studentList.Any(o => o.StudentName.Equals("John")) 
                     && studentList.Any(o => o.StudentName.Equals("Ram"));

将导致获取学生列表2次,我是否可以检查在一个条件下列表中是否存在多个值?

using System;
using System.Linq;
using System.Collections.Generic;

                    
public class Program
{
    public static void Main()
    {
        // Student collection
        IList<Student> studentList = new List<Student>() { 
                new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
                new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } 
            };
        
        // LINQ Query Syntax to find out teenager students
        
        var bool_check = studentList.Any(o => o.StudentName.Equals("John")) 
            && studentList.Any(o => o.StudentName.Equals("Ram"));

        Console.WriteLine(bool_check);
    }
}

public class Student 
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}
plupiseo

plupiseo1#

如果找到“John”,当前条件将搜索列表两次。如果要避免此问题,可以同时筛选“John”和“Ram”,然后选中此较小的列表,例如:

var shortList = studentList
                  .Where(x => x.StudentName == "John" 
                              || x.StudenName == "Ram")
                  .ToHashSet();
var bool_check = shortList.Contains("John") && shortList.Contains("Ram);

但是,只要您在内存中有列表,并且大小不是太大,差异就会很微妙。

6l7fqoea

6l7fqoea2#

List<string> DesireNames = new List<string>(){"John", "Ram"};
var YourFilteredStudents = ShortList.Where(o=> DesireNames.Contains(o.StudentName ));
f4t66c6m

f4t66c6m3#

在性能上没有什么大的区别,但在语法上,您可以使用多个条件,如下所示:

IList<Student> studentList = new List<Student>() {
                new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
                new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
            };

var test = from s in studentList
           where (s.StudentName!=null && s.StudentName!="") && (s.StudentName.Contains("John") || s.StudentName.Contains("Ram"))
           select s;

foreach (var item in test)
{
    Console.WriteLine($"id: {item.StudentID} name : {item.StudentName}");
}

Console.ReadKey();

通过这种方式,您可以在"where"中应用所有必要的过滤器,就好像它是单个条件一样

相关问题