250 likes | 509 Views
LINQ. Language Integrated Query. Čo je to LINQ. Language Integrated Query Najd ôležitejšia novinka C # 3.0 a .NET 3.5 Linq integruje syntax dotazov priamo do jazyka C# a umo žnoje prístup k rôznym dátovým zdrojom Pri každom dátovom zdroji sú dotazy v podstate totožné
E N D
LINQ Language Integrated Query
Čo je to LINQ • Language Integrated Query • Najdôležitejšia novinka C# 3.0 a .NET 3.5 • Linqintegruje syntax dotazovpriamo do jazyka C# a umožnoje prístup k rôznym dátovým zdrojom • Pri každom dátovom zdroji sú dotazy v podstatetotožné • Syntax je podobná SQL
LINQ a List<> • Ukážka výberu z listu pomocou delegátov IEnumerable<Racer> brazilChampions = champions.Where( r => r.Country = =“Brazil”).OrderByDescending( delegate(Racer r) { return r.Wins; }).Select( delegate(Racer r) { return r; });
Lambda výrazy • Nová syntax anonymných metód • Je možné ich použiť na miestach, kde pracujeme s delegátmi Public delegate bool Predicate(intobj, string s); Predicate p = (cislo, slovo) => cislo > 5 && slovo = “adasd”
Ukážka lamba výrazov a LINQ List<Racer> champions = new List<Racer>(Formula1.GetChampions()); IEnumerable<Racer> brazilChampions = champions. Where(r => r.Country == "Brazil"). OrderByDescending(r => r.Wins). Select(r => r); varquery = from r in Formula1.GetChampions() where r.Country == "Brazil" orderby r.Wins descending select r;
Ukážky použitia jednotlivých operátorov Filtrovanie var racers = from r in Formula1.GetChampions() where r.Wins > 15 && (r.Country == “Brazilie”) select r; Filtrovaniepomocoupočítadla var racers = from r in Formula1.GetChampions().Where( (r, index) => r.LastName.StartsWith(“A”) && index % 2 != 0);
Filtrovanie podľa typu object[] data = {“jeden”, 2, 3, “štyri”, päť, 6}; var query = data.OfType<string>; Zložené from var ferrariDrivers = from r in Formula1.GetChampions() from c in r.Cars where c == “Ferrari” orderbyr.LastName select r.FirstName + “ “ + r.LastName;
Usporiadanie Var racers = from r in Formula1.GetChampions() where r.Country == “Brazílie” ordery r.Wins descending select r; Usporiadanie s použitím metód OrderBy() a ThenBy() Var racers = Formula1.GetChampions(). OrderBy(r => r.Country). ThenBy(r => r.LastName). ThenBy(r => r.FirstName). Take(10);
Zoskupovanie (agregácia) + vnútorné objekty Var countries = from r in Formula1.GetChampions() group r by r.Countryinto g orderbyg.Count(), g.Key where g.Count() >= 2 select new { Country = g.Key, Count = g.Count(), Racers = from r1 in g orderby r1.LastnName select r1.FirstName + r1.LastName }; Foreach(var item in countries) { ….item.Country, item.Count foreach(var name in item.Racers) { ….name.FirstName, name.LastName }
Spájanie(join) Var racers ….. Var teams ….. Var racersAndTeams = from r in racers join t in teams on r.Year equals t.Year select new { Year = r.Year, Racer = r.Name, Team = t.Name}; Alebojedným dotazom Var racersAndTeams = from r in Formula1.GetChampions() ….. join t in Formula.GetConstructerChampions() ….. on r.Year equals t.Year select new {…..}
LINQ to SQL • Microsoft vytvoril LINQ akotenkú obálku, ktorá poskytuje silne typové rozhranie pre dátové úložisko • Pomocou LINQu môžete pristupovať k dátam ako k objektom • Je to najjednoduchší spôsob písania dotazov • Visual Studio 2008 s LINQ to SQL silne spolupracuje a poskytuje užívateľské rozhranie (O/R Designer)
Objekty LINQ to SQL • Databáza -> Datacontext • Tabuľka -> Trieda a kolekcia • Stĺpec -> Vlastnosť • Vzťah -> Vnorená kolekcia • Uložená procedúra -> Metodá
DataContext • Tentoobjektza vás riadi transakcie v databáze Add new Item -> Linq to SQL Classes -> Databaza.dbml DataContext db = new DataContext(connectionString); DatabazaDataContext db = new DatabazaDataContext(); Var article = db.ExecuteQuery<Article>(“SELECT * FROM Articles”, “”);
Dotazy v LINQ a v SQL LINQ Var query = from a in db.Articles select a; SQL SELECT [t0].[ArticleID], [t0].[Author], [t0].[CreatedDate], [t0].[ValidFrom], [t0].[ValidTo], [t0].[Title], [t0].[Content], [t0].[CategoryID] FROM [dbo].[Articles] AS [t0]
Update Article article = data.Articles.Single(a => a.ArticleID == args.ArticleID); article.Author = ...; article.CategoryID = ...; article.Content = ...; article.CreatedDate = …; article.ValidFrom = …; article.ValidTo = …; data.SubmitChanges();
Insert,Delete Datacontext.InsertOnSubmit(…); Datacontext.DeleteOnSubmit(…); DataContext.SubmitChanges();
LINQ to XML • Podobné dotazy ako LINQ to SQL, ale nie totožné • Nová trieda Xdocument, je náhradou XmlDocument. Praca s Xdocument je jednoduchšie.Pracuje s ďalšími objektami Xnamespace, Xcomment, Xelement, Xattribute Ukažka pridávania elementu do XML XDocumentxdoc = Xdocument.Load(@”C:\Companies.xml”); Xelement xe = new Xelement(“Company”, “Datapac”); Xdoc.Element(“Companies”).Add(xe);
Dotaz LINQ to XML Xdocument xdoc = Xdocument.Load(@”adresa”); Xdocument xdoc = Xdocument.Parse(string xml); Var query = from rssFeed in xdoc.Descendant(“channel”) select new { Title = rssFeed.Element(“Title”).Value Description = rssFeed.Element(“Description”).Value }
Zložitejšie dotazy var query = from partner in xml.Descendants("Partner").Where(p =>) from partnership in partner.Descendants("Partnership").Where(p =>) from station in xml.Descendants("Station").Where(s => ) from saddress in station.Descendants("Address") select new ListItem(station.Attribute("SID").Value, station.Element("DID").Value, station.Element("Name").Value, partner.Element("First_name").Value, partner.Element("Last_name").Value, saddress.Element("Street").Value, saddress.Element("Number").Value, saddress.Element("Municipality").Value, saddress.Element("Zip_code").Value);
LINQ to SQL a LINQ to XML Xelementxe = new XElement("Articles", from a in db.Articles select new XElement("Article", new XAttribute("ID", a.ArticleID), new XElement("Title", a.Title), new XElement("Author", a.Author), new XElement("Category", a.Category.Name))); xe.Save(@"C:\articles.xml");
Links 101 LINQ Examples • http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx LINQ to SQL vs. ADO.NET • http://agilior.pt/blogs/pedro.rainho/archive/2008/07/02/4935.aspx