我可以檢查以下兩個條件,但在性能方面,有沒有更好的方法來做到這一點?當串列包含 StudentName 為 John 和 Ram 的記錄時,我希望它回傳 true。如果只有 John,則需要回傳 false
studentList.Any(o => o.StudentName.Equals("John"))
&& studentList.Any(o => o.StudentName.Equals("Ram"));
會導致兩次獲取學生串列,我可以在一個條件下檢查串列中是否存在多個值嗎?
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; }
}
uj5u.com熱心網友回復:
如果找到“John”,當前條件將搜索串列兩次。如果你想避免這種情況,你可以過濾“John”和“Ram”并檢查這個較小的串列,例如:
var shortList = studentList
.Where(x => x.StudentName == "John"
|| x.StudenName == "Ram")
.ToHashSet();
var bool_check = shortList.Contains("John") && shortList.Contains("Ram);
但是,只要您在記憶體中有串列并且大小不是太大,差異就會很微妙。
uj5u.com熱心網友回復:
List<string> DesireNames = new List<string>(){"John", "Ram"};
var YourFilteredStudents = ShortList.Where(o=> DesireNames.Contains(o.StudentName ));
uj5u.com熱心網友回復:
在性能方面沒有什么大的不同,但在語法上,您可以使用多個條件,如下所示:
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”中,您可以應用所有必要的過濾器,就好像它是一個條件一樣
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/510526.html
標籤:C#林克
上一篇:為什么我的主機作業系統無法訪問我的docker網路網關IP
下一篇:tomcat上部署jenkins
