栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C#系 常用的LinQ查询表达式之select

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#系 常用的LinQ查询表达式之select

select子句指定所选定的对象哪部分应该被选择。类似于Sql 语句中的Select

List stuList = new List()
{
    new Student(){ID=1,Name="LiLei",Age=22},
    new Student(){ID=2,Name="JingJing",Age=19},
    new Student(){ID=3,Name="Json",Age=31},
    new Student(){ID=4,Name="Mary",Age=40} ,
};
Console.WriteLine("-------------1 查找所有-------------");
var stu = from s in stuList 
            select s;
foreach (var item in stu)
{
    Console.WriteLine(item.Name);
}

根据我们的要查找字段的类型来创建

List stuList = new List()
{
    new Student(){ID=1,Name="LiLei",Age=22},
    new Student(){ID=2,Name="JingJing",Age=19},
    new Student(){ID=3,Name="Json",Age=31},
    new Student(){ID=4,Name="Mary",Age=40} ,
};


Console.WriteLine("-------------2 查询某个字段-------------");
stu = from s in stuList 
        where s.Name.ToString().StartsWith("J") 
        select s;
foreach (var item in stu)
{
    Console.WriteLine(item.Name);
}


select 查询表达式可以在我们查询的时候帮助我们创建一个匿名类型的对象,一般在我们不需要传递参数的时候可以直接使用

List stuList = new List()
{
    new Student(){ID=1,Name="LiLei",Age=22},
    new Student(){ID=2,Name="JingJing",Age=19},
    new Student(){ID=3,Name="Json",Age=31},
    new Student(){ID=4,Name="Mary",Age=40} ,
};
    
Console.WriteLine("-------------3 创建匿名类型对象-------------");
var stu2 = from s in stuList
        where s.Name.ToString().StartsWith("J")
        select new { s.ID, s.Name };
foreach (var item in stu2)
{
    Console.WriteLine(item.Name);
}

如果在后续过程中需要用到查询结果的明确的类型,那么可以通过在创建对象的时候直接指明对象

Console.WriteLine("-------------4创建对象-------------");
var stu3 = from s in stuList
            where s.Name.ToString().StartsWith("J")
            select new Student { ID = s.ID, Name = s.Name };


foreach (var item in stu3)
{
    Console.WriteLine(item.Name);
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908682.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号