一、LINQ查询符列表
|
Query Operators |
Meaning in Life |
|
from, in |
Used to define the backbone for any LINQ expression, which allows you to extract a subset of data from a fitting container. |
|
where |
Used to define a restriction for which items to extract from a container. |
|
select |
Used to select a sequence from the container. |
|
join, on, equals, into |
Performs joins based on specified key. Remember, these “joins” do not need to have anything to do with data in a relational database. |
|
orderby, ascending, descending |
Allows the resulting subset to be ordered in ascending or descending order. |
|
group, by |
Yields a subset with data grouped by a specified value. |
另外还有一些没有操作符号,而是以扩展函数(泛型函数)的方式提供的函数:
用不同方式产生结果集: Reverse<>(), ToArray<>(), ToList<>()
集合操作: Distinct<>(), Union<>(), Intersect<>()
统计函数: Count<>(), Sum<>(), Min<>(), Max<>()
二、使用Enumerable获取Counts
为了使用这些Enumerable扩展函数,一般把LINQ查询表达式用括号括起来,先转换为IEnumerable<T>兼容的对象。
{
string[] currentVideoGames = {"Morrowind", "BioShock",
"Half Life 2: Episode 1", "The Darkness",
"Daxter", "System Shock 2"};
// Get count from the query.
int numb = (from g in currentVideoGames
where g.Length > 6
orderby g
select g).Count<string>();
// numb is the value 5.
Console.WriteLine("{0} items honor the LINQ query.", numb);
}
基本语法
in container
orderby value ascending/descending
select item;
1、获取全部记录
2、只获取字段名称
3、使用Enumerable.Distinct<T>()
foreach (var n in names)
{
Console.WriteLine("Name: {0}", n);
}
Console.WriteLine("Distinct makes:");
foreach (var m in makes.Distinct<string>())
{
Console.WriteLine("Make: {0}", m);
}
var onlyBMWs = from c in myCars where c.Make == "BMW" select c;
var onlyFastBMWs = from c in myCars where c.Make == "BMW" && c.Speed >= 100 select c;
6、Reverse<T>()
foreach (Car c in subset)
{
Console.WriteLine("{0} is going {1} MPH", c.PetName, c.Speed);
}
或者
foreach (Car c in subset.Reverse<Car>())
{
Console.WriteLine(c.ToString());
}
默认是ascending
var subset = from c in myCars orderby c.PetName select c;
// and order by descending PetName
subset = from c in myCars
where c.Speed > 55 orderby c.PetName descending select c;
默认顺序时也可以明确指明
orderby c.PetName ascending select c;
8、Enumerable.Except()
两个IEnumerable<T>兼容的对象的差集
{
List<string> myCars = new List<String>
{ "Yugo", "Aztec", "BMW"};
List<string> yourCars = new List<String>
{ "BMW", "Saab", "Aztec" };
.Except(from c2 in yourCars select c2);
Console.WriteLine("Here is what you don't have, but I do:");
foreach (string s in carDiff)
Console.WriteLine(s); // Prints Yugo.
}
var q = from p in db.Products
group p by p.CategoryID into g
where g.Count() >= 10
select new {
g.Key,
ProductCount = g.Count()
};
//多列
var categories =
from p in db.Products
group p by new
{
p.CategoryID,
p.SupplierID
} into g
select new
{
g.Key,
g
};
//表达式(Expression)
var categories =
from p in db.Products
group p by new { Criterion = p.UnitPrice > 10 } into g
select g;
浙公网安备 33010602011771号