Here is a example of using yield:

public static IEnumerable<int> Unique(IEnumerable<int> nums)
{
Dictionary<int, int> uniqueVals = new
Dictionary<int, int>();
foreach (int num in nums)
{
if (!uniqueVals.ContainsKey(num))
{
uniqueVals.Add(num, num);
yield return num;
}
}
}


Dompare the typical way and the "yield" to get IEnumerable

# IList<string> FindBobs(IEnumerable<string> names)  
# {
# var bobs = new List<string>();
#
# foreach(var currName in names)
# {
# if(currName == "Bob")
# bobs.Add(currName);
# }
#
# return bobs;
# }
# IEnumerable<string> FindBobs(IEnumerable<string> names)  
# {
# foreach(var currName in names)
# {
# if(currName == "Bob")
# yield return currName;
# }
# }



 
Categories: C# | LINQ and C# 3.0

Sometime I need resort the ArrayList or List<T> in my code. I am too lazy to write a piece of code to implement IComparer. When I search through google, I found there is a very elegant way to do the sorting:
[code]
peopleList.Sort(
delegate(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}
);

peopleList.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

[/code]
I have used code like this many times, but actually I didn't really understand why code can be wrote like this.
Those are some different way to sorting in different version of .net frameworks,
and those articles helping me to understand the sorting code better.

Thanks to happy九拍
如果不用匿名方法,我们1.1里就的这么写

代码:
static int Compare(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}
然后
代码:
people.Sort(new Comparison<Preson>(Compare));
你的问题解决了,在C#3.0里,我们不再需要匿名方法了,直接lambda咯
代码:
people.Sort((p1, p2) => p1.name.CompareTo(p2.name));

Thanks to Shadal:
2.0可以这样写
static int Compare(Person p1, Person p2)
{
return p1.name.CompareTo(p2.name);
}

people.Sort(Compare);





An userful article:

Variable Scoping in Anonymous Delegates in C#


public void AddScript(ScriptItem script)
{
    ScriptItem match = null;
 
    // *** Grab just the path
    if (!string.IsNullOrEmpty(script.Src))
    {
        script.FileId = Path.GetFileName(script.Src).ToLower();
 
        match = this.InternalScripts.Find(
            delegate(ScriptItem item)
            {
               ScriptRenderModes mode = this.RenderMode;  // demonstrate this pointer
               return (item.FileId == script.FileId);
            });
    }
 
    if (match == null)                
        this.InternalScripts.Add(script);
    else
        match = script;
} 


 
Categories: C# | LINQ and C# 3.0