在LinkedList中搜索具有自定义对象。我们可以使用Find()或Contains() [英] Search in LinkedList has custom object. Can we use Find() or Contains()
本文介绍了在LinkedList中搜索具有自定义对象。我们可以使用Find()或Contains()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类,一个LinkedList是有Employee对象的列表。现在需要根据姓名搜索员工。像list.Contains(emp.empName)假设或其他任何东西。
I have following class, a LinkedList is there has list of Employee object. Now need to search an employee according to name. Like list.Contains(emp.empName) suppose or any thing else.
class Employee
{
int empId;
string empName;
double basicSal;
Employee(int eid, string name, double bsal)
{
empId = eid;
empName = name;
basicSal = bsal;
}
static void Main(string[] args)
{
LinkedList<Employee> list = new LinkedList<Employee>();
//List of employees
list.AddFirst(new Employee(1, "Sam",9000));
list.AddLast(new Employee(2, "Jeet", 10000));
list.AddLast(new Employee(3, "John", 11000));
}
}
谢谢你。
Thank You.
推荐答案
LINQ 的?类似于:
var result = list.Where(emp => emp.empName == "TheName");
或
var result = list.FirstOrDefault(emp => emp.empName == "TheName");
我找到了一个解决方案。
对于上述情况,我认为我们不能使用Contins()或Find()。
但是使用ToArray()
I came to one solution.
For the above case i think we cannot use Contins() or Find().
But use ToArray()
Console.Write("Enter a name for search: ");
string n = Console.ReadLine();
Employee[] emparr=new Employee[list.Count];
emparr = list.ToArray();
int c = 0;
for (c = 0; c < list.Count; c++)
{
if (emparr[c].empName == n)
{
break;
}
}
Console.WriteLine("Name is: "+emparr[c].empId+" Basic Salary is: "+emparr[c].basicSal);
Can we use Find() or Contains() method instead ??
这篇关于在LinkedList中搜索具有自定义对象。我们可以使用Find()或Contains()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文