我该如何将以下SQL查询转换为C#中的LINQ查询形式,.NET 3.5代码: 1)
select COUNT(distinct Skill_Name)
from Table1
where Department = 'ABC' and Skill_Name is not null
2)
select distinct location, country from Customer where Customer_Code ='1001';
我该如何将以下SQL查询转换为C#中的LINQ查询形式,.NET 3.5代码: 1)
select COUNT(distinct Skill_Name)
from Table1
where Department = 'ABC' and Skill_Name is not null
2)
select distinct location, country from Customer where Customer_Code ='1001';
我怀疑您需要:
var query = from entry in dbContext.Table1
where entry.Department == "ABC" && entry.SkillName != null
select entry.SkillName;
var count = query.Distinct().Count();
或者使用扩展方法语法,一次完成:
var count = dbContext.Table1
.Where(entry => entry.Department == "ABC" &&
entry.SkillName != null)
.Select(entry => entry.SkillName)
.Distinct()
.Count();
如mesiesta所示,您可以将查询表达式与不支持查询表达式的调用组合起来,但我倾向于将查询表达式分配给一个中间变量...个人认为这样更清晰,但请使用您(和您的团队)喜欢的方法。
Count()
调用。当你将结果取到数据表时,你可以计算结果的数量。 - Jon SkeetCount()
调用。我不知道如何将数据传输到现有的 DataTable
中,但是您可以使用LINQ to DataSet扩展方法从查询结果创建一个新的 DataTable
。请参见DataTableExtensions.CopyToDataTable。 - Jon Skeet类似于这样的
int count = (from p in Table1
where p.Department == "ABC" && p.Skill_Name != null
select p.Skill_Name).Distinct().Count();
var query= (from p in Customer
where p.Customer_Code=="1001"
select new { Location=p.location ,Country=p.country}).Distinct();
您可以使用 LinqPad 将表达式转换为 Linq 和 Lambda 表达式。