c语言query函数的用法(C10.)
c语言query函数的用法(C10.)varQuerySyntax=fromobjinintegerList whereobj>5 selectobj;完整代码示例:fromobjectinDataSource where[condition] selectobject;设置查询条件:对象大于 53、在数据源中执行查询语句下面让我们来演示不同的 LINQ 查询语句写法简单的查询表达式:分别有:数据初始化、条件表达式、对象选取表达式组成
前言:LINQ(语言集成查询)是 C#编程语言中的一部分。它在.NET Framework 3.5 和 C#3.0 被引入,在 System.Linq 命名空间中使用。LINQ 为我们提供了通用的查询语法,该语法使我们能够查询来自各种数据源的数据。这意味着我们可以从各种数据源(如 SQL Server 数据库,XML 文档,ADO.NET 数据集)以及任何其他内存中对象(如 Collections,Generics 等)查询获取或更新设置数据。
编写 LINQ 查询,我们需要三个步骤:
1、定义或引入数据源(内存中的对象,SQL,XML)
2、编写询问语句
3、在数据源中执行查询语句
下面让我们来演示不同的 LINQ 查询语句写法
1. LINQ 查询语句表达式语法简单的查询表达式:分别有:数据初始化、条件表达式、对象选取表达式组成
fromobjectinDataSource
where[condition]
selectobject;
设置查询条件:对象大于 5
varQuerySyntax=fromobjinintegerList
whereobj>5
selectobj;
完整代码示例:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
namespaceCsharp
{
classDemo
{
staticvoidMain(string[]args)
{
//数据源
List<int>integerList=newList<int>()
{
1 2 3 4 5 6 7 8 9 10
};
//LINQ方法1:查询表达式
varQuerySyntax=fromobjinintegerList
whereobj>5
selectobj;
Console.WriteLine("LINQ方法1:查询表达式");
//执行LINQ查询
foreach(variteminQuerySyntax)
{
Console.Write(item "");
}
Console.ReadKey();
}
}
}
输出大于 5 的对象:6 7 8 9 10
2. LINQ 对象方法表达式语法
简单的对象表达式语法,即将数据源对象扩展查询方法
DataSource.ConditionMethod([Condition]).SelectMethod();
扩展数据源对象 Where 查询方法
varMethodSyntax=integerList.Where(obj=>obj>5).ToList();
完整代码示例:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
namespaceCsharp
{
classDemo
{
staticvoidMain(string[]args)
{
//数据源
List<int>integerList=newList<int>()
{
1 2 3 4 5 6 7 8 9 10
};
//LINQ方法2:对象表达式
varMethodSyntax=integerList.Where(obj=>obj>5).ToList();
Console.WriteLine("LINQ方法2:对象表达式");
//执行LINQ查询
foreach(variteminMethodSyntax)
{
Console.Write(item "");
}
Console.ReadKey();
}
}
}
输出大于 5 的对象:6 7 8 9 10
3. LINQ 2 种语法混合使用
两种查询语法也可以混合使用
先使用查询语句表达式语法将数据筛选,然后通过对象方法表达式,返回数据之和
varMethodSyntax=(fromobjinintegerList
whereobj>5
selectobj).Sum();
完整代码示例:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
namespaceCsharp
{
classDemo
{
staticvoidMain(string[]args)
{
//数据源
List<int>integerList=newList<int>()
{
1 2 3 4 5 6 7 8 9 10
};
//LINQ方法3:2种语法混合使用
varHybridMethod=(fromobjinintegerList
whereobj>5
selectobj).Sum();
Console.WriteLine("LINQ方法3:2种语法混合使用");
//执行LINQ查询
Console.Write($"数据之和为:{HybridMethod}");
Console.ReadKey();
}
}
}
先筛选大于 5 的对象:6 7 8 9 10,再对这些对象求和
输出:40
今天我们给大家分享了,C#语言中LINQ查询的3种语法,大家都学会了吗?
欢迎关注公众号:KnowHub 知识加油站!