LINQ

From no name for this wiki
Jump to: navigation, search

Hier einige LINQ Samples. Mircrosofts LINQ Sample Page: 101 LINQ Samples

Collections Queries

Hello World

Namespace System.Linq hinzufuegen und Referenz auf Assembly System.Core.dll

 int[] numbers = {1,2,3,4,5,6,7,8,9};
 var lowNums = from n in numbers where n < 5 select 5;
 foreach (int i in lowNums)
 {
  Console.WriteLine(i);
 }

Schreibt 5,5,5,5,5,5,5,5,5

LINQ und Extension Methods

res1 und res2 sind gleich.

int[] x = { 213, 1234, 23423, 243 };
var res1 = from t in x where t > 1000 select t;
var res2 = x.Where(n => n>1000);
foreach (int elem in res1)
{
   Console.Write(elem);
}
foreach (int elem in res2)
{
   Console.Write(elem);
}

Sehr einfach

 int[] numbers = { 1, 2 };
 var x = from n in numbers select 5;

Var ist [5, 5]

IGrouping

 int[] numbers = { 1, 2, 3,4,5,6,7,8,9 };
 IEnumerable<IGrouping<int, int>> result = numbers.GroupBy(n => n % 2);
 foreach(IGrouping<int, int> grouping in result){
  int key = grouping.Key;
  Console.WriteLine("Key:" + key);
  List<int> list = grouping.ToList();
  foreach (int elemInGroup in list)
  {
   Console.Write(" ," + elemInGroup);   
  }
 }

Schreibt zwei Listen: Key 1 [1,3,5,7,9] und Key 0 [2, 4, 6, 8].

Mehrere sourcen

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
 
var pairs =
  from a in numbersA
  from b in numbersB
     where a < b
     select new {a, b};
int count = pairs.Count();
Console.WriteLine(count);
foreach(var elem in pairs){
    Console.Write(elem.a);
    Console.Write(elem.b);
}

XML Queires

Simple

  XDocument xdocument = XDocument.Load(@"C:\data\project.xml");
  IEnumerable<XElement> descendants = xdocument.Descendants();
  IEnumerable<string> result = from tmp in descendants select tmp.Value;
  foreach (string y in result)
  {
   Console.WriteLine(y.ToString());
  }

Where Clause

 XDocument xdocument = XDocument.Load(@"C:\data\project.xml");   
 IEnumerable<XElement> descendants = xdocument.Descendants();
 IEnumerable<string> result = from tmp in descendants where tmp.Name.LocalName.Equals("type") select tmp.Value;
 foreach (string y in result)
 {
  Console.WriteLine(y.ToString());
 }

Select Bean

 XDocument xdocument = XDocument.Load(@"C:\data\project.xml");   
 IEnumerable<XElement> descendants = xdocument.Descendants();
 IEnumerable<Bean> result = from tmp in descendants 
                            where tmp.Name.LocalName.Equals("type") 
                            select new Bean(tmp.Value, tmp.Name.LocalName);
            foreach (Bean y in result)
            {
                Console.WriteLine(y.ToString());
            }

Namespaces

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace XmlParser
{
    class Program
    {
        static void Main(string[] args)
        {
 
            XDocument xdoc = XDocument.Load("Sample.xml");
            XNamespace f = "http://www.w3schools.com/furniture";
 
            XName xname = f + "table";
            IEnumerable<XElement> result = 
                        from x in xdoc.Descendants(xname)
                        select x;
            foreach(XElement e in result)
            {
                string t = e.Value;
            }
 
        }
    }
}

Dataset queries

Standard

           DataTable tableToQuery = dataSet.Tables["ParentTable"];
            var queryable = tableToQuery.AsEnumerable();
            var queryResult = from theThing in queryable 
                              where theThing.Field<Int32>("id") > 1 
                              select new { Id = theThing.Field<Int32>("id"), Value = theThing.Field<String>("ParentItem") };
            foreach (var item in queryResult)
            {
                Console.WriteLine(item.Id);
                Console.WriteLine(item.Value);
            }

Query operators

           DataTable tableToQuery = dataSet.Tables["ParentTable"];
            var enumerable = tableToQuery.AsEnumerable();
            var result = enumerable.Where(blabla => blabla.Field<Int32>("id") > 1);
            var result2 = result.Select(blabla => new { Id = blabla.Field<Int32>("id"), Value = blabla.Field<String>("ParentItem") });
            foreach (var item in result2)
            {
                Console.WriteLine(item.Id);
                Console.WriteLine(item.Value);
            }

Database Queries

Siehe MSDN

Unterschied von LINQ to SQL zu LINQ to Entities: linq to sql vs. linq to entities

Hello World

Datenbanktabelle anlegen mit zwei Rows (id und name) mit dem Namen MyTable. Dann zur Tabelle eine Entityklasse anlegen:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Reflection;
using System.Linq.Expressions;
using System.ComponentModel;
 
namespace Ado2Demo
{
    [Table(Name = "dbo.MyTable")]
    class CraftedTable
    {
 
		private int _id;
 
		private string _name;
 
        public CraftedTable()
		{
		}
 
		[Column(Storage="_id", AutoSync=AutoSync.Always, DbType="Int NOT NULL IDENTITY", IsDbGenerated=true)]
		public int id
		{
			get
			{
				return this._id;
			}
			set
			{
				if ((this._id != value))
				{
					this._id = value;
				}
			}
		}
 
		[Column(Storage="_name", DbType="NVarChar(500)")]
		public string name
		{
			get
			{
				return this._name;
			}
			set
			{
				if ((this._name != value))
				{
					this._name = value;
				}
			}
		}
    }
}

Dann ein LINQ Query absetzten:

       private void button1_Click(object sender, EventArgs e)
        {
            DataContext dc = new DataContext(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDb2.mdf;Integrated Security=True;User Instance=True");
 
            Table<CraftedTable> table = dc.GetTable<CraftedTable>();
            var q =  from c in table              
               select c;
            foreach (var row in q)
            {
                Console.WriteLine("id = {0}, Name = {1}", row.id, row.name);
            }            
        }

1 to many association

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Reflection;
using System.Linq.Expressions;
using System.ComponentModel;
 
namespace Ado2Demo
{
    [Table(Name = "dbo.MyTable")]
    public class CraftedTable
    {
 
		private int _id;		
		private string _name;
        private EntitySet<ChildTable> _children;
 
        public CraftedTable()
		{
		}
 
		[Column(Storage="_id", DbType="Int NOT NULL IDENTITY", IsDbGenerated=true, IsPrimaryKey=true)]
		public int id
		{
			get
			{
				return this._id;
			}
			set
			{
				if ((this._id != value))
				{
					this._id = value;
				}
			}
		}
 
		[Column(Storage="_name", DbType="NVarChar(500)")]
		public string name
		{
			get
			{
				return this._name;
			}
			set
			{
				if ((this._name != value))
				{
					this._name = value;
				}
			}
		}
 
        [Association(Storage = "_children", OtherKey = "parentid")]
        public EntitySet<ChildTable> Children
        {
            get { return this._children; }
            set { this._children.Assign(value); }
        }
 
 
 
    }
 
    [Table(Name = "dbo.Table2")]
    public class ChildTable
    {
        private int _id;
        private int _parentid;
        private string _name;
        private EntityRef<CraftedTable> _parentobject;  
 
        [Column(Storage = "_id", DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true, IsPrimaryKey=true)]
        public int id
        {
            get
            {
                return this._id;
            }
            set
            {
                if ((this._id != value))
                {
                    this._id = value;
                }
            }
        }
 
        [Column(Storage = "_parentid", AutoSync = AutoSync.Always, DbType = "Int", Name="mytableid")]
        public int parentid
        {
            get
            {
                return this._parentid;
            }
            set
            {
                if ((this._parentid != value))
                {
                    this._parentid = value;
                }
            }
        }
 
		[Column(Storage="_name", DbType="NVarChar(500)")]
		public string name
		{
			get
			{
				return this._name;
			}
			set
			{
				if ((this._name != value))
				{
					this._name = value;
				}
			}
		}
 
        [Association(Storage = "_parentobject", ThisKey = "parentid")]
        public CraftedTable ParentObject
        {
            get { return this._parentobject.Entity; }
            set { this._parentobject.Entity = value; }
        }
 
    }
 
 
}