Linq

هي لغة استعلام تستخدم مع اي مصدر بيانات لتبحث فيه وتجلب لك النتائج . (A query is an expression that retrieves data from a data source)
لنفترض ان لدينا البيانات التالية

players = new List<Player>();
players.Add(new Player("mazen",12,"A"));
players.Add(new Player("mohammed", 18, "A"));
players.Add(new Player("amr", 16, "B"));
players.Add(new Player("karim", 22, "B"));
players.Add(new Player("fofo", 30, "B"));
players.Add(new Player("mooz", 15, "C"));

 

Select
public void query1()
{
    var q = from p in players  select p.name;
    foreach(string p in q)
        print(p);
}
//mazen,mohammed,amr,karim,fofo,mooz

 

Filtering
public void query2()
{
     var q = from p in players where p.age>15 select p.name;
     foreach (string p in q)
         print(p);
}
//mohammed,amr,karim,fofo
public void query3()
{
     var q = from p in players where p.age>15 && p.@group=="A" select p.name;
     foreach (string p in q)
         print(p);
}
//mohammed

 

Ordering(asccending or descending )
public void query4()
{
     var q = from p in players orderby p.age ascending select p.name;
     foreach (string p in q)
         print(p);
}
//mazen,mooz,amr,mohammed,karim,fofo

وفي حال كان Player is implement IComparable

public void query4()
{
     var q = from p in players orderby p ascending select p.name;
     foreach (string p in q)
         print(p);
}
//mazen,mooz,amr,mohammed,karim,fofo
public void query4()
 {
     var q = from p in players
             where p.@group == "A"
             orderby p ascending select p.name;
     foreach (string p in q)
         print(p);
}
//mazen,mohammed

 

Grouping
public void query5()
{
        var q = from p in players
                where p.age>20
                orderby p ascending
                group p by p.@group into grs
                select grs;

        foreach (var p in q)
        {
            foreach(Player pp in p)
                print(p.Key+" : "+pp.name);
        }
}
//B : karim
//B : fofo

 

Joining
public void query6()
{
        string[] groups = { "A","C" };
        var q = from p in players
                join grs in groups on p.@group equals grs 
                select new Player(p.name,p.age,grs);

        foreach (var p in q)
        {
           print(p.name);
        }
}
 //mazen,mohammed,mooz

 

linq with xml
void linq1(XDocument doc)
{
     var res = from element in doc.Root.Descendants("Player")
               where element.Attribute("group").Value == "A"
               select element.Element("Name");

     foreach (var str in res)
         print(str.Value);
}


التصنيف : c#