欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中Linq查询基本操作使用实例

程序员文章站 2024-02-19 22:03:10
摘要:本文介绍linq查询基本操作(查询关键字) - from 子句 - where 子句 - select子句 - group 子句 - into 子...

摘要:本文介绍linq查询基本操作(查询关键字)

- from 子句

- where 子句

- select子句

- group 子句

- into 子句

- orderby 子句

- join 子句

- let 子句

- 复合from子句

- 在某些情况下,源序列中的每个元素本身可能是序列(集合),也可能包含序列

- 用语访问单个数据库中的内部集合

- 使用多个from字句执行连接

- 可以包含多个可从独立数据源生成补充查询的from字句

复合(顾名思义就是有多from的字句)实例:

复制代码 代码如下:

class program
{ static void main(string[] args)
    {
        list<student> students = new list<student> { new student
            {
                lastname="xiaogui",scores=new list<int>{97,42,91,60}}, new student
                {
                    lastname="xiaozhan",scores=new list<int>{50,92,81,60}}, new student
                    {
                        lastname="xiaolan",scores=new list<int>{32,32,81,90}}, new student
                        {
                            lastname="xiaowan",scores=new list<int>{92,22,81,60}},        
        }; var query = from stuent in students from score in stuent.scores where score > 90 select new {
                        last = stuent.lastname,
                        score
                    }; foreach (var student in query)//大于90分的显示出来   {
            console.writeline("{0} score:{1}", student.last, student.score);
        }
        console.readline();
    }
}

复制代码 代码如下:

public class student
{ public string lastname { get; set; } public list<int> scores { get; set; }
} public class employee
{ public string first { get; set; } public string last { get; set; } public int id { get; set; }
}

执行结果: xiaogui score:97

              xiaogui score:91

              xiaozhan score:92

              xiaowan score:92

let 关键字(使用let字句扩展范围变量)

- 创建一个可以查询自身的可枚举类型

- 使查询只能对范围变量word调用一次tolower。

如果不使用let,则必须在where字句的每个谓词中调用tolower

例:把每个单词开头包含a或者e的找出来

复制代码 代码如下:

using system; using system.linq; public class test
{ static void main(string[] args)
    { string[] strings = { "a penny saved is a penny earned.", "the aaxly sdj", "the pa is no" }; var query = from sentence in strings
                    let words = sentence.split(' ')//用空格分割成数组  from word in words
                    let w = word.tolower()//把每个字母小写  where w[0] == 'a' || w[0] == 'e' select word; foreach (var s in query)
        {
            console.writeline(s);
        }
        console.readline();
    }
}

where 关键字 (筛选)

- 一个查询表达式可以包含多个where字句

例:(把包含a的找出来)

复制代码 代码如下:

using system; using system.linq; public class test
{ static void main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str where s == "a" select s; foreach (var s in query)
        {
            console.writeline(s);
        }
        console.readline();
    }
}

orderby 关键字 (排序)

- 在查询表达式中,orderby字句可以使返回的序列(组)按升序或降序。

- 可以指定多个键,以便执行一个或多个次要排序操作

- 默认排序顺序为升序

- 编译时,orderby字句被转换为对orderby方法的调用。orderby字句中的多个键被转换为thenby方法调用

descending 降序

ascending 升序

例1:升序

复制代码 代码如下:

using system; using system.linq; public class test
{ static void main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str orderby s ascending select s;
    }
}

结果为: a b c

例2:降序

复制代码 代码如下:

using system; using system.linq; public class test
{ static void main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str orderby s descending select s;
    }
}

结果为: c b a

group 关键字 (分组)

- group 字句返回一个igrouping(tkey,telement)对象序列 

- 编译时,group子句被转换为对groupby方法的调用

(linq查询表达式可以以select或者group结束) (如果想要对每个组执行附加查询操作,则可以使用into上下文关键字指定一个临时标识符,使用into时,必须继续编写该查询,并最终用一个select语句或另一 个group子句结束该查询)

例:

复制代码 代码如下:

using system; using system.linq; public class test
{ static void main(string[] args)
    { string[] str = { "aa", "bb", "cc", "dd" }; var query = from s in str
                    group s by s[0]
                        into p where p.key == 'a' || p.key == 'b' || p.key == 'c' orderby p.key descending select p.key; foreach (var s in query)
        {
            console.writeline(s);
        }
        console.readline();
    }
}

结果为: c b a

说明: group s by s[0] into p 意思是针对范围变量s用“s[0]”分组,本例中是用第一个字母分组

join 关键字 (联接)

- 使用join 子句可以将来自不同源序列并且在对象模型中没有直接关系的元素相关联

- 唯一的要求是每个源中的元素需要共享某个可以进行比较以判断是否相等的值

- join字句使用特殊的equals关键字比较指定的键是否相等

三中常见的连接类型

- 内部联接

- 分组联接

- 左外部联接

1.内部联接

复制代码 代码如下:

var query = from a in str
join b in str2 on a.id equals b.id select new { aname = a.name, bname = b.name };

2.分组联接:(into 可以将join暂存起来)

复制代码 代码如下:

var query = from a in str
join b in str2 on a.id equals b.id
into c select new {aname=a.name,cs=c}

3.左外部联接

- 在左外部联接中,将返回左则源序列中所有元素,即使它们在右则序列中没有匹配的元素也是如此。

- 若要在linq中执行左外部联接,请将defaultifempty方法与分组联接结合起来,以指定要在某个左则元素不具有匹配元素时产生的默认右则元素。可以使用null作为任何引

用类型的默认值,也可以指定用户定义的默认类型。

复制代码 代码如下:

var query = from category in categories
join prod in products on category.id equals prod.categoryid
into prodgroup from item prodgroup.defaultifempty( new product{name=string.empty,categoryid=0}) select new {catname=category.name,prodname=item.name}

equalse 运算符

- join 子句执行同等联接。换句话说,只能基于两个键之间的相等关系进行匹配

- 为了表明所有联接都是相等联接,join子句使用equals关键字而不是==运算符

复合键

- 使用复合键可以测试多个值是否相等

select 关键字 选择