Con C# Linq (.NET 3.5) è possibile estrarre da una collezione di oggetti un insieme che soddisfa una determinata condizione (Where). Una volta estratti è possibile ciclarli con un semplice forech
C#
public class TestLinq
{
  public int ID { get; set; }
  public string Name { get; set; }
  public DateTime Modified { get; set; }
  public override string ToString()
  {
    return string.Format("ID:{0}, Name:{1}, Modified:{2}", ID, Name, Modified);
  }
}
public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    //sample data
    List<TestLinq> entities = new List<TestLinq>()
    {
      new TestLinq{ID=1, Name="Milano", Modified=new DateTime(2009,06,8)}
      ,new TestLinq{ID=2, Name="Monza", Modified=new DateTime(2009,06,28)}
      ,new TestLinq{ID=3, Name="Lecco", Modified=DateTime.Now}
      ,new TestLinq{ID=4, Name="Como", Modified=DateTime.Now.AddDays(-1)}
      ,new TestLinq{ID=4, Name="Pavia", Modified=new DateTime(2009,06,27)}
    };

    System.Diagnostics.Debug.WriteLine("-7----------------");
    // sample 7 - where and order
    var find7 = entities.Where(t => t.Name.Contains("n")).OrderByDescending(x => x.Name);
    foreach(var i in find7){
      System.Diagnostics.Debug.WriteLine(i);
    }

    System.Diagnostics.Debug.WriteLine("-8----------------");
    // sample 8 - where with delegate
    var find8 = entities.Where(delegate(TestLinq t)
    { 
      return t.Name.Contains("n");
    });
    foreach(var i in find8){
      System.Diagnostics.Debug.WriteLine(i);
    }

    System.Diagnostics.Debug.WriteLine("-9----------------");
    // sample 9 - linq query with where and order by
    var find9 = from c in entities
                orderby c.Name descending
                where c.ID > 2 && c.Modified < DateTime.Now
                select c;
    foreach (var i in find9)
    {
      System.Diagnostics.Debug.WriteLine(i);
    }
                
  }
}
L'esempio da come risultato:
-7----------------
ID:2, Name:Monza, Modified:28/06/2009 0.00.00
ID:1, Name:Milano, Modified:08/06/2009 0.00.00
-8----------------
ID:1, Name:Milano, Modified:08/06/2009 0.00.00
ID:2, Name:Monza, Modified:28/06/2009 0.00.00
-9----------------
ID:4, Name:Pavia, Modified:27/06/2009 0.00.00
ID:3, Name:Lecco, Modified:29/06/2010 0.11.36
ID:4, Name:Como, Modified:28/06/2010 0.11.36
Potrebbe interessarti anche: