2014-10-21 62 views
1

我想了解LINQ發佈之前C#代碼的樣子。比較LINQ之前的代碼

我已經嘗試過尋找這個好幾個星期,然後空了。我理解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); 
} 

你如何能夠通過排序和按姓氏查找僱員的名字並顯示出來?

+1

'for' /'foreach' +'if' .. – 2014-10-21 21:59:41

+0

你是不是要求排序,但用於過濾 – CheGueVerra 2014-10-21 22:09:45

+0

雖然大部分的答案是給代碼的典型的時代,[yield return](http://msdn.microsoft.com/en-us/library/9k7k7cf0%28v=vs.80%29.aspx)確實繼續LINQ。理解「收益回報」對於理解LINQ的許多運營商來說至關重要。 – 2014-10-22 00:13:33

回答

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); 
} 
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類,並傳遞給排序方法

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是這樣一個節省時間:)

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) 
    } 
}