我试图了解在LINQ问世之前c#代码的样子。
我已经尝试了几个星期的搜索并且空了。我理解LINQ是如何工作的,但是你说你有一个对象列表但是你试图找到一小部分。在LINQ之前你会怎么做?
LINQ示例(请原谅我的语法错误,我还在学习):)
list<employee> newlist = new List<employee> {john, smith, 30}
newlist.add{jane, smith, 28}
newlist.add{greg, lane, 24}
var last
from name in newlist
where name.last.equals("smith")
select name
foreach(var name in last)
{
Console.WriteLine(last);
}
您如何按姓氏排序并找到员工姓名并显示它们?
答案 0 :(得分:2)
只是传统的方式。循环并过滤。
var smiths = new List<string>();
foreach (var employee in newlist)
{
if(employee.Last == "smith")
{
smiths.Add(employee);
}
}
return smiths;
对于排序,您可以将委托传递给Sort()方法。 LINQ只是语法糖。
newlist.Sort(delegate(Employee e1, Employee e2)
{
//your comparison logic here that compares two employees
});
排序的另一种方法是创建一个实现IComparer的类并将其传递给sort方法
newlist.Sort(new LastNameComparer());
class LastNameComparer: IComparer<Employee>
{
public int Compare(Employee e1, Employee e2)
{
// your comparison logic here that compares two employees
return String.Compare(e1.Last, e2.Last);
}
}
查看所有这些代码,LINQ可以节省时间:)
答案 1 :(得分:2)
它的代码行数真的相同,只是更多的花括号。这是翻译:
List<employee> newList = new List<employee>
{
new employee {First = john, Last = smith, Age = 30},
new employee {First = jane, Last = smith, Age = 28},
new employee {First = greg, Last = lane, Age = 24},
}
// Original code: // Pre-Linq translation:
var last // Becomes: var last = new List<employee>();
from name in newList // Becomes: foreach (var name in newList) {
where name.Last.Equals("smith") // Becomes: if (name.Last.Equals("smith") {
select name // Becomes: last.Add(name) } }
// Pre-Linq code:
var last = new List<employee>();
foreach (var name in newList)
{
if (name.Last.Equals("smith")
{
last.Add(name)
}
}
答案 2 :(得分:0)
非常简单。您正在遍历列表中的所有项目并将(正在复制对其他列表的引用)复制到您要查找的项目中:
var smiths = new List<Persons>();
// get all Smiths and print them
foreach(var item in newlist)
{
if(item.last == "smith")
smiths.Add(item);
}
foreach(var item in smiths)
{
Console.WriteLine(item);
}