在使用Linq轉化XML,ActiveDirectory,Datatable,Array,List,Dictionary后意識到Linq的強大。VS居然還提供專門的LINQ Explorer,不覺明厲啊~

好用的 Linq Samples and the Sample Query Explorer

http://blog.miniasp.com/post/2008/05/05/About-Linq-Samples-and-the-Sample-Query-Explorer.aspx



該solution是直接使用MDF文件的,自己裝個Northwind,把connection string改下

AttachDBFileName='C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples\LinqSamples\SampleQueries\Data\NORTHWND.MDF';Server='.\SQLEXPRESS';user instance=true;Integrated Security=SSPI;Connection Timeout=60

Data Source=Localhost;Initial Catalog=Northwind;Integrated Security=True



1.查詢Datatbale的值

var q = from dr in ds.Tables[0].AsEnumerable()

            select new {Name = dr["Name"].ToString().Trim(),Age=dr["Age"].ToString().Trim()};



2.Join multiple string for group by rows

var employees = new List<Employee>();
employees.Add(new Employee { Name = "A", Age = 30, ContactNo = "New Contact Number A", Salary = 20000 });
employees.Add(new Employee { Name = "A", Age = 30, ContactNo = "New Contact Number A", Salary = 20000 });
employees.Add(new Employee { Name = "B", Age = 31, ContactNo = "New Contact Number B", Salary = 30000 });
employees.Add(new Employee { Name = "C", Age = 32, ContactNo = "New Contact Number C", Salary = 40000 });
employees.Add(new Employee { Name = "C", Age = 32, ContactNo = "New Contact Number C", Salary = 40000 }); var customers = new List<Customer>();
customers.Add(new Customer { Name = "A", Age = 30, ContactNo = "Old Contact Number A" });
customers.Add(new Customer { Name = "B", Age = 31, ContactNo = "New Contact Number B" }); var q2 = from e in employees
group e by new { name = e.Name, age = e.Age } into pg
select new Customer
{
Name = pg.Key.name,
Age = pg.Key.age,
ContactNo = String.Join(",", pg.Select(o => o.ContactNo).ToList())
};

3.對List<T>的distinct操作必須定義GetHashCode() 和Equals方法才能成功

不然的話,就只能用group by了

public partial class Person
{
public String Name { get; set; }
public Int AGe { get; set; } public override bool Equals(object obj)
{
if (obj == null)
return false; if (this.GetType() != obj.GetType())
return false; return Equals(obj as Person);
} private bool Equals(Person p)
{
return (this.Name == =p.Name && this.Age == p.Age);
} public override int GetHashCode()
{
return this.GetHashCode();
} }

4.Left join

var q4 = from e in employees
join c in customers on e.Name equals c.Name into g
from lg in g.DefaultIfEmpty()
select new { Name = e.Name, Age = e.Age, ContactNo1 = e.ContactNo, ContactNo2 =(lg==null)?"NULL":lg.ContactNo };
Console.WriteLine("Left Join Results:");
foreach (var c in q4)
{
Console.WriteLine(string.Format("Name:{0} Age:{1} ContactNo1:{2} ContactNo2:{3}", c.Name, c.Age, c.ContactNo1, c.ContactNo2));
}







How to: Perform Left Outer Joins (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/bb397895.aspx



5.Update

我比較意外Method1可以成功。。。

// Method1
employees.Where(w => w.Name == "A" || w.Name == "C").ToList().ForEach(f => f.Salary = 5000);
Console.WriteLine("Method1:");
foreach (Employee e in employees)
{
Console.WriteLine(string.Format("Name:{0} Age:{1} ContactNo:{2} Salary:{3}", e.Name, e.Age, e.ContactNo , e.Salary));
}
// Method2
var updateEmps = employees.Where(w => w.Name == "A" || w.Name == "C");
foreach(Employee e in updateEmps){
e.Salary = 6000;
}
Console.WriteLine("Method2:");
foreach (Employee e in employees)
{
Console.WriteLine(string.Format("Name:{0} Age:{1} ContactNo:{2} Salary:{3}", e.Name, e.Age, e.ContactNo, e.Salary));
}





6.Multiple fields join



var q3 = from e in employees

     join c in customers on new { e.Name, e.Age } equals new { c.Name, c.Age }

     select e;



7.Multiple insert linq result int database

.Net Framework 4.5 似乎有AsDatatable()和CopyToDataTable,如果沒有自己寫一個也可以

Converting a List to Datatable

http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list-to-datatable

.NET Framework 4.5  CopyToDataTable Method

http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.copytodatatable(v=vs.110).aspx

            public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table; } DataTable dt = new DataTable();
String[] colStrs = new string[] { 。。。};
String[] colDts = new string[] {。。。};
String[] colInts = new string[] { 。。。}; foreach (string col in colStrs) { dt.Columns.Add(new DataColumn(col, typeof(string))); }
foreach (string col in colDts) { dt.Columns.Add(new DataColumn(col, typeof(DateTime))); }
foreach (string col in colInts) { dt.Columns.Add(new DataColumn(col, typeof(Int32))); } using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
{ var q = from e in db.TestTable
where e.Id > 10
select e; DataTable dt2 = ConvertToDataTable( q.ToList());// q.CopyToDataTable();
bulkCopy.DestinationTableName = "TestTable";
foreach (string col in colStrs) { bulkCopy.ColumnMappings.Add(col, col); }
foreach (string col in colDts) { bulkCopy.ColumnMappings.Add(col, col); }
foreach (string col in colInts) { bulkCopy.ColumnMappings.Add(col, col); }
bulkCopy.WriteToServer(dt2);
}

8.   Create XML document           

public void LinqToSqlLocalMethodCall02()

{

    XDocument doc = new XDocument(

        new XElement("Customers", from c in db.Customers

                                  where c.Country == "UK" || c.Country == "USA"

                                  select (new XElement("Customer",

                                      new XAttribute("CustomerID", c.CustomerID),

                                      new XAttribute("CompanyName", c.CompanyName),

                                      new XAttribute("InterationalPhone", PhoneNumberConverter(c.Country, c.Phone))

                                      ))));

Console.WriteLine(doc.ToString());

}

9. Sum()

public void LinqToSqlCount03() {

    var q = db.Orders.Select(o => o.Freight).Sum();

    Console.WriteLine(q);

}

public void LinqToSqlCount04() {

    var q = db.Products.Sum(p => p.UnitsOnOrder);

    Console.WriteLine(q);

}

10.group by count()

public void LinqToSqlJoin05() {

    var q =

        from c in db.Customers

        join o in db.Orders on c.CustomerID equals o.CustomerID into orders

        select new {c.ContactName, OrderCount = orders.Count()};

ObjectDumper.Write(q);

}

11.union

public void LinqToSqlUnion01() {

    var q = (

             from c in db.Customers

             select c.Phone

            ).Concat(

             from c in db.Customers

             select c.Fax

            ).Concat(

             from e in db.Employees

             select e.HomePhone

            );

ObjectDumper.Write(q);

}

public void LinqToSqlUnion04() {

    var q = (

             from c in db.Customers

             select c.Country

            ).Intersect(

             from e in db.Employees

             select e.Country

            );

ObjectDumper.Write(q);

}

public void LinqToSqlUnion05() {

    var q = (

             from c in db.Customers

             select c.Country

            ).Except(

             from e in db.Employees

             select e.Country

            );

ObjectDumper.Write(q);

}

12.Like

public void LinqToSqlSqlMethods01()

{

var q = from c in db.Customers

            where SqlMethods.Like(c.CustomerID, "C%")

            select c;

ObjectDumper.Write(q);

}

13.DateDiffDay

public void LinqToSqlSqlMethods02()

{

var q = from o in db.Orders

            where SqlMethods.DateDiffDay(o.OrderDate, o.ShippedDate) < 10

            select o;

ObjectDumper.Write(q);

}

14.CompiledQuery

public void LinqToSqlCompileQuery01()

{

    //Create compiled query

    var fn = CompiledQuery.Compile((Northwind db2, string city) =>

        from c in db2.Customers

        where c.City == city

        select c);

Console.WriteLine("****** Call compiled query to retrieve customers from London ******");

    var LonCusts = fn(db, "London");

    ObjectDumper.Write(LonCusts);

Console.WriteLine();

Console.WriteLine("****** Call compiled query to retrieve customers from Seattle ******");

    var SeaCusts = fn(db, "Seattle");

    ObjectDumper.Write(SeaCusts);

}

15.linq to dictionary

public void LinqToSqlConversion04() {

    var q =

        from p in db.Products

        where p.UnitsInStock <= p.ReorderLevel && !p.Discontinued

        select p;

Dictionary<int, Product> qDictionary = q.ToDictionary(p => p.ProductID);

foreach (int key in qDictionary.Keys) {

        Console.WriteLine("Key {0}:", key);

        ObjectDumper.Write(qDictionary[key]);

        Console.WriteLine();

    }

}

var db = new EmpServiceDataContext();

var q = (from s in db.ChineseCheckInfos

    select new { s.EmployerCode ,s.CheckCode,s.CheckName})

    .ToDictionary(s=>s.EmployerCode +s.CheckCode,s=>s.CheckName);

Dictionary<string, string> chnCheckNames = q;

16.Direct SQL

public void LinqToSqlDirect01() {

    var products = db.ExecuteQuery<Product>(

        "SELECT [Product List].ProductID, [Product List].ProductName " +

        "FROM Products AS [Product List] " +

        "WHERE [Product List].Discontinued = 0 " +

        "ORDER BY [Product List].ProductName;"

    );

ObjectDumper.Write(products);

}

Console.WriteLine("*** UPDATE ***");

    db.ExecuteCommand("UPDATE Products SET UnitPrice = UnitPrice + 1.00");

16. Linq to Store procedure   

public void LinqToSqlStoredProc02() {

    ISingleResult<CustomersByCityResult> result = db.CustomersByCity("London");

ObjectDumper.Write(result);

}

 

 

  public void LinqToSqlStoredProc04() {

    IMultipleResults result = db.GetCustomerAndOrders("SEVES");

Console.WriteLine("********** Customer Result-set ***********");

    IEnumerable<CustomerResultSet> customer = result.GetResult<CustomerResultSet>();

    ObjectDumper.Write(customer);

    Console.WriteLine();

Console.WriteLine("********** Orders Result-set ***********");

    IEnumerable<OrdersResultSet> orders = result.GetResult<OrdersResultSet>();

    ObjectDumper.Write(orders);

}

17.Linq to string array compare the length and value

public void Linq5() {

    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

var shortDigits = digits.Where((digit, index) => digit.Length < index);

Console.WriteLine("Short digits:");

    foreach (var d in shortDigits)

    {

        Console.WriteLine("The word {0} is shorter than its value.", d);

    }

}

Short digits:

The word five is shorter than its value.

The word six is shorter than its value.

The word seven is shorter than its value.

The word eight is shorter than its value.

The word nine is shorter than its value.

18.Table to Dictionary

connDbConnection_forTemp = new System.Data.OleDb.OleDbConnection();

connDbConnection_forTemp.ConnectionString = conString;

connDbConnection_forTemp.Open();

System.Data.OleDb.OleDbCommand objCommand = new System.Data.OleDb.OleDbCommand();

string sqlStr = "select * from AMS_MailSetting where MailSetting like '" + prefix + "%'";

objCommand.CommandText = sqlStr;

objCommand.Connection = connDbConnection_forTemp;

DataSet ds = new DataSet();

System.Data.OleDb.OleDbDataAdapter objAdaptor = new System.Data.OleDb.OleDbDataAdapter();

objAdaptor.SelectCommand = objCommand;

objAdaptor.Fill(ds);

if (ds.Tables[0].Rows.Count > 0)

{

  var q = from dr in ds.Tables[0].AsEnumerable()

    select (new KeyValuePair<string, string>(dr["MailSetting"].ToString(), dr["SettingParam"].ToString()));

  values = q.ToDictionary(s =>s.Key,s=>s.Value);

   // value = ds.Tables[0].Rows[0][0].ToString();

}

19.居然还可以动态列名排序!

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyStr) where TEntity : class
{
ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");
PropertyInfo property = typeof(TEntity).GetProperty(propertyStr);
Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
LambdaExpression le = Expression.Lambda(propertyAccessExpression, param);
Type type = typeof(TEntity);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(le));
return source.Provider.CreateQuery<TEntity>(resultExp);
}

Linq初体验——Order By 通过属性名动态排序

http://www.cnblogs.com/xxfss2/archive/2010/12/13/1905023.html



Linq To Sql进阶系列(六)用object的动态查询与保存log篇

http://www.cnblogs.com/126/archive/2007/09/09/887723.html

強悍的Linq的更多相关文章

  1. 【WIN10】程序內文件讀取與保存

    DEMO下載:http://yunpan.cn/cFHIZNmAy4ZtH  访问密码 cf79 1.讀取與保存文件 Assets一般被認為是保存用戶文件數據的地方.同時,微軟還支持用戶自己創建文件夾 ...

  2. linux下 ip指令

    目录 Network ip command Command :ip 简介 内容 Network ip command Command :ip 简介 ip 是個指令喔!並不是那個 TCP/IP 的 IP ...

  3. 第五章、 Linux 常用網路指令

    http://linux.vbird.org/linux_server/0140networkcommand.php     第五章. Linux 常用網路指令 切換解析度為 800x600 最近更新 ...

  4. Linq表达式、Lambda表达式你更喜欢哪个?

    什么是Linq表达式?什么是Lambda表达式? 如图: 由此可见Linq表达式和Lambda表达式并没有什么可比性. 那与Lambda表达式相关的整条语句称作什么呢?在微软并没有给出官方的命名,在& ...

  5. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  6. [C#] 走进 LINQ 的世界

    走进 LINQ 的世界 序 在此之前曾发表过三篇关于 LINQ 的随笔: 进阶:<LINQ 标准查询操作概述>(强烈推荐) 技巧:<Linq To Objects - 如何操作字符串 ...

  7. [C#] 进阶 - LINQ 标准查询操作概述

    LINQ 标准查询操作概述 序 “标准查询运算符”是组成语言集成查询 (LINQ) 模式的方法.大多数这些方法都在序列上运行,其中的序列是一个对象,其类型实现了IEnumerable<T> ...

  8. LINQ to SQL语句(7)之Exists/In/Any/All/Contains

    适用场景:用于判断集合中元素,进一步缩小范围. Any 说明:用于判断集合中是否有元素满足某一条件:不延迟.(若条件为空,则集合只要不为空就返回True,否则为False).有2种形式,分别为简单形式 ...

  9. .NET深入实战系列—Linq to Sql进阶

    最近在写代码的过程中用到了Linq查询,在查找资料的过程中发现网上的资料千奇百怪,于是自己整理了一些关于Linq中容易让人困惑的地方. 本文全部代码基于:UserInfo与Class两个表,其中Cla ...

随机推荐

  1. Linux IO模式以及select poll epoll详解

    一 背景 同步IO和异步IO,阻塞IO和非阻塞IO分别是什么,到底有什么区别?不同的人在不同的上下文下给出的答案是不同的.所以先限定一下本文的上下文. 本文讨论的背景是Linux环境下的network ...

  2. HDU - 2196(树形DP)

    题目: A school bought the first computer some time ago(so this computer's id is 1). During the recent ...

  3. Django新手入门必看

    pip install django==2.1.7 (现在Django3.0出来,推荐大家可以使用一下Django3.0) pip list查看

  4. Pygame小游戏练习三

    @Python编程从入门到实践 Python项目练习 七.创建Passenger类 创建passenger.py文件,创建Passenger类,控制乘客属性和行为 # passenger.py imp ...

  5. HTML form表单中action的正确写法

    我的Java Web Application的context是myweb,即http://localhost:8080/myweb/index.jsp是欢迎页. 现在我的一个Controller的映射 ...

  6. margin:0 auto;生效条件

    1.position:absolute下不生效 原因:position:absolute只能相对于父元素进行定位top.left定位,相当于浮在父元素上面,所以margin:0 auto;就没有了参考 ...

  7. makemigrations和migrate到底干了什么以及如何查询原生的sql语句

    在你改动了 model.py的内容之后执行下面的命令: python manger.py makemigrations 相当于 在该app下建立 migrations目录,并记录下你所有的关于mode ...

  8. VmWare 网络模式

    VMware虚拟机三种联网方法及原理 一.Brigde--桥接:默认使用VMnet0 1.原理: Bridge 桥"就是一个主机,这个机器拥有两块网卡,分别处于两个局域网中,同时在" ...

  9. JS 实现继承的方法 ES6 and ES5

    继承 ES6 方法  (类的继承) ES6中有一个属性的 extends 语法: ​ • class Father {} ​ • class Son extends Father{} ​ 注意:是子类 ...

  10. 小程序wxs是作用

    wxs weixin script,小程序的脚本语言:可以结合wxml构建页面结构: 说白了 就是在小程序里面写函数表达式的地方: wxml里面直接使用wxs,有错误再次刷新就能解决 <wxs ...