C# Linq基本常用用法

时间:2023-08-31 21:19:14

1.什么是Linq?

  Lanaguage Interated Query(语言集成查询),Linq 是集成C# 和VB这些语言中用于提供数据查询能力的一个新特性。

  这里只介绍两种基本常用用法。

  学习方法参考示例代码

1) where  查询

 class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { , , , , , , , , , };
var result = from m in nums where m >= select m;
foreach (var v in result)
{
Console.WriteLine("v:" + v + " ");
}
Console.WriteLine("\n"); //使用Lambda 表达式进行Linq查询
var result2 = nums.Where(m => m >= );
foreach (var v in result2)
{
Console.WriteLine("v2:" + v + " ");
} List<People> mans = new List<People>();
mans.Add(new People { id = , sex = true, name = "小王", birthday = Convert.ToDateTime("1994-1-1") });
mans.Add(new People { id = , sex = false, name = "小张", birthday = Convert.ToDateTime("1954-1-1") });
mans.Add(new People { id = , sex = true, name = "小明", birthday = Convert.ToDateTime("1993-1-1") });
mans.Add(new People { id = , sex = false, name = "小红", birthday = Convert.ToDateTime("1974-1-1") }); var resultMan = from man in mans where man.id < && man.sex select man;
foreach (var v in resultMan)
{
Console.WriteLine("v:"+v.id + " name :"+v.name);
}
Console.Read();
}
} class People
{
public string name { get; set; }
public int id { get; set; }
public bool sex { get; set; }
public DateTime birthday { get; set; }
public int GetAge()
{
return DateTime.Now.Year - birthday.Year;
}
} C# Linq基本常用用法

2) order 排序

descending 降序

ascending 升序

   List<int> numbers = new List<int>() { , , , , , ,  };

             var resultNums = from m in numbers orderby m  select m;
foreach (var v in resultNums)
{
Console.WriteLine("v num:"+v);
}
Console.WriteLine("\n");
var resultNums2 = from m in numbers orderby m descending select m;
foreach (var v in resultNums2)
{
Console.WriteLine("v2 num:" + v);
}
Console.WriteLine("\n"); var resultNums3 = from m in numbers orderby m ascending select m;
foreach (var v in resultNums3)
{
Console.WriteLine("v3 num:" + v);
}

C# Linq基本常用用法

2.优点

  1.简单,容易上手,极大节省开发效率。

   2.很大程度上节省代码量。

建议:Unity开发的话,一般都不要去使用,会产生GC。

参考链接:http://www.cnblogs.com/jara/p/3472215.html  http://www.cnblogs.com/hgmyz/p/7068150.html