当前位置:网站首页>C#中Linq用法汇集
C#中Linq用法汇集
2022-07-02 22:10:00 【kalvin_y_liu】
C#中Linq常用用法
1、linq中交集、并集、差集的用法
简单的交集、并集、差集用法如下:
List<string> ListA = new List<string>();
List<string> ListB = new List<string>();
List<string> ListResult = new List<string>();
ListResult = ListA.Distinct().ToList();//去重
ListResult = ListA.Except(ListB).ToList();//差集
ListResult = ListA.Union(ListB).ToList(); //并集
ListResult = ListA.Intersect(ListB).ToList();//交集
若上面的例子不是List类型,而是List,则需要对XXXModel进行处理。
步骤如下:
(1)先定义Model。
public class ItemModel
{
public string ItemCode {
get; set; }
public string ItemName {
get; set; }
}
(2)定义如何Model间如何比较。若不定义,比较的是两个引用。
public class ItemModelComparer : IEqualityComparer<ItemModel>
{
//比较
public bool Equals(ItemModel x, ItemModel y)
{
bool checkFlag = true;
if (Object.ReferenceEquals(x, y))
{
checkFlag = true;
}
else if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
checkFlag = false;
}
else
{
if (x.ItemCode == y.ItemCode)
{
checkFlag = true;
}
else
{
checkFlag = false;
}
}
return checkFlag;
}
//实现获取哈希值
public int GetHashCode(ItemModel model)
{
if (Object.ReferenceEquals(model, null)) return 0;
int hashNurse = model.ItemCode.GetHashCode();
return hashNurse;
}
}
(3)具体使用如下
List<ItemModel> ListA = new List<ItemModel>();
List<ItemModel> ListB = new List<ItemModel>();
List<ItemModel> ListResult = new List<ItemModel>();
ListResult = ListA.Distinct(new ItemModelComparer()).ToList();//去重
ListResult = ListA.Except(ListB, new ItemModelComparer()).ToList();//差集
ListResult = ListA.Union(ListB, new ItemModelComparer()).ToList(); //并集
ListResult = ListA.Intersect(ListB, new ItemModelComparer()).ToList();//交集
2、 join的用法
若出现两个List,想用Linq进行查询。则可以使用如下的方式
int tempSatisfiedConditionCount = (from r1 in whiteList
join r2 in args.DiagList on r1.DiagCode equals r2.DiagCode
select r1).Count();
多条件的join
//多条件的联合查核
List<DiagControlModel> whiteDiagList = (from r1 in diagControlList
where r1.ControlRelation == 1
join r2 in args.DiagList on new {
code = r1.DiagCode, name = r1.DiagName }
equals new{
code=r2.DiagCode,name=r2.DiagName}
select r1).ToList<DiagControlModel>();
另外,join还可以用于左连接/右连接
var LeftJoin = from emp in ListOfEmployees
join dept in ListOfDepartment
on emp.DeptID equals dept.ID into JoinedEmpDept
from dept in JoinedEmpDept.DefaultIfEmpty()
select new
{
EmployeeName = emp.Name,
DepartmentName = dept != null ? dept.Name : null
};
3、let用法
let是一个在linq中定义局部变量
1、可以有多个let子句
2、let后的变量无需声明类型
参见下例:
var query = from a in list
let b = a.Name.Split('-')
let c=a.Age
where b[0] =="zhangs" & c>21
select a;
4、分组
常用的分组用法
var linqtest = from r in db.Am_recProScheme
orderby r.rpId descending
group r by r.recType into n
select new
{
n.Key, //这个Key是recType
rpId = n.Sum(r => r.rpId), //组内rpId之和
MaxRpId = n.Max(r => r.rpId),//组内最大rpId
MinRpId = n.Min(r => r.rpId), //组内最小rpId
};
略微复杂点:
var dataList= (from r in drugLabelList
group r by new
{
r.OrderNo,
r.PatientID,
r.PatientName
} into q
let drugAmount = q.Sum(t => Convert.ToInt32(t.ChargeAmount))
where drugAmount >= 0
select new PrintDrugLabelModel
{
OrderNo = q.Key.OrderNo,
PatientID = q.Key.PatientID,
PatientName = q.Key.PatientName,
ChargeAmount = ""+drugAmount
}).ToList<PrintDrugLabelModel>();
//1
var ss = from r in db.Am_recProScheme
orderby r.rpId descending
group r by r.recType into n
select new
{
n.Key, //这个Key是recType
rpId = n.Sum(r => r.rpId), //组内rpId之和
MaxRpId = n.Max(r => r.rpId),//组内最大rpId
MinRpId = n.Min(r => r.rpId), //组内最小rpId
};
foreach (var t in ss)
{
Response.Write(t.Key + "--" + t.rpId + "--" + t.MaxRpId + "--" + t.MinRpId);
}
//2
var ss1 = from r in db.Am_recProScheme
orderby r.rpId descending
group r by r.recType into n
select n;
foreach (var t in ss1)
{
Response.Write(t.Key + "--" + t.Min(p => p.rpId));
}
//3
var ss2 = db.Am_recProScheme.GroupBy(p => p.recType);
foreach (var t in ss2)
{
Response.Write(t.Key + "--" + t.Min(p => p.rpId));
}
//4
string sssql = "select recType,min(rpId),max(rpId),sum(rpId) from Am_recProScheme group by recType"; //多字段 var result = (from item in data group item by new { item.Name, item.Type } into items select new { items.Key.Name, items.Key.Type, Cnt = items.Count() }).ToList(); var s = data.GroupBy(p => new { p.Type, p.Name }).Select(p=>new { p.Key.Type, p.Key.Name, cnt=p.Count() }).ToList();
5、简单的函数计算
var linqtest = (from r in db.Am_recProScheme
select r).Sum(p => p.rpId);
6、排序order by desc/asc
var linqtest = (from r in db.Am_recProScheme
where r.rpId > 10
orderby r.rpId descending //倒序
// orderby r.rpId, r.rpname descending //多条件的倒序(与SQL语句中的相同)
// orderby r.rpId ascending //正序
select r);
7、top(1)
//如果取最后一个可以按倒叙排列再取值
var linqtest = (from r in db.Am_recProScheme
select r).FirstOrDefault();
8、跳过前面多少条数据取余下的数据
var linqtest = (from r in db.Am_recProScheme
where r.rpId > 10
orderby r.rpId descending
select r).Skip(10).Take(10); //取第11条到第20条数据
9、包含
//可以使用List、Array、string的Contains()方法进行判断
var linqtest = (from r in db.Am_recProScheme
where r.SortsText.Contains("张")
select r);
10、连接查询
var linqtest = (from r in db.Am_recProScheme
join w in db.Am_Test_Result on r.rpId equals w.rsId
orderby r.rpId descending
select r);
11、使用linq查询DataTable
//遍历DataTable,将其中的数据对应到ClientStruct中:
List<ClientStruct> list = (from x in dtTable.AsEnumerable()
orderby x.Field<string>("") descending
where x.Field<string>("ErrorType") == "漏孔"
select new ClientStruct
{
ID = x.Field<string>(cs.ID),
Name = x.Field<string>(cs.Name),
Company = x.Field<string>(cs.Company),
CreatedDate = x.Field<string>(cs.CreatedDate)
}).ToList<ClientStruct>();
12、linq中列传行操作(Aggregate的使用)—2022-3-4
解决分组又聚合的问题。
后台数据存储的样式是:

希望实现:
即:实现分组,并且能将诊断进行聚合(列转行)
linq的写法如下:
var data_list = (from r in temp_result_list
group r by new
{
r.DrugCode,
r.VisitType
} into q
select q.Aggregate(temp_result_list[0],(workingSentence, next) => new DiagControlModel
{
DrugCode = q.Key.DrugCode,
VisitType = q.Key.VisitType,
DiagInfoStr = workingSentence.DiagInfoStr + ";" + next.DiagName
})).ToList<DiagControlModel>();
13.分页数据查询
//1
var ss = (from r in db.Am_recProScheme
where r.rpId > 10
orderby r.rpId descending
select r).Skip(10).Take(10); //取第11条到第20条数据
//2 Take(10): 数据从开始获取,获取指定数量(10)的连续数据
var ss1 = db.Am_recProScheme.OrderByDescending(p => p.rpId).Where(p => p.rpId > 10).Skip(10).Take(10).ToList();
//3
string sssql = "select * from (select ROW_NUMBER()over(order by rpId desc) as rowNum, * from [Am_recProScheme]) as t where rowNum>10 and rowNum<=20";
14.sql中的In
//1
var ss = from p in db.Am_recProScheme
where (new int?[] {
24, 25,26 }).Contains(p.rpId)
select p;
foreach (var p in ss)
{
Response.Write(p.Sorts);
}
//2
string st = "select * from Am_recProScheme where rpId in(24,25,26)";
边栏推荐
- Splunk audit 的设定
- [Yangcheng cup 2020] easyphp
- Strictly abide by the construction period and ensure the quality, this AI data annotation company has done it!
- LC173. 二叉搜索树迭代器
- Webrtc audio and video capture and playback examples and mediastream media stream analysis
- Generics and reflection, this is enough
- Jerry's built-in shutdown current is 1.2ua, and then it can't be turned on by long pressing [chapter]
- Comprehensively analyze the logic of the shared purchase business model? How sharing purchase empowers Enterprises
- [chestnut sugar GIS] ArcMap - why should the tick of classic capture be removed when using custom capture?
- 深度剖析数据在内存中的存储----C语言篇
猜你喜欢

Uniapp wechat login returns user name and Avatar

PMP project integration management

LeetCode 968. 监控二叉树

Brief introduction of emotional dialogue recognition and generation

Strictly abide by the construction period and ensure the quality, this AI data annotation company has done it!

Detailed explanation and application of merging and sorting

Typical case of data annotation: how does jinglianwen technology help enterprises build data solutions

The motivation of AES Advanced Encryption Protocol

Jinglianwen technology's low price strategy helps AI enterprises reduce model training costs

Application of containerization technology in embedded field
随机推荐
Xiaopeng P7 had an accident and the airbag did not pop up. Is this normal?
Qt QSplitter拆分器
xshell配置xforward转发火狐浏览器
P1007 single log bridge
World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
用matlab调用vs2015来编译vs工程
Golang's learning route
Lc173. Binary search tree iterator
Chow-Liu Tree
數據分析學習記錄--用EXCEL完成簡單的單因素方差分析
The first batch of Tencent cloud completed the first cloud native security maturity assessment in China
编辑卡顿
Go 4 modes Singleton
stop slave卡住--事务的事件没有复制完整
Go four singleton modes
Motivation du Protocole de chiffrement avancé AES
数据分析学习记录--用EXCEL完成简单的单因素方差分析
ServletContext learning diary 1
boot actuator - prometheus使用
Lambda表达式:一篇文章带你通透