当前位置:网站首页>Common usage of LINQ in C #
Common usage of LINQ in C #
2022-06-29 10:26:00 【zlbcdn】
1、linq Middle intersection 、 Combine 、 The use of difference sets
Simple intersection 、 Combine 、 The difference set is used as follows :
List<string> ListA = new List<string>();
List<string> ListB = new List<string>();
List<string> ListResult = new List<string>();
ListResult = ListA.Distinct().ToList();// duplicate removal
ListResult = ListA.Except(ListB).ToList();// Difference set
ListResult = ListA.Union(ListB).ToList(); // Combine
ListResult = ListA.Intersect(ListB).ToList();// intersection
If the above example is not List<string> type , It is List<XXXModel>, You need to XXXModel To deal with .
Steps are as follows :
(1) First define Model.
public class ItemModel
{
public string ItemCode {
get; set; }
public string ItemName {
get; set; }
}
(2) How to define Model How to compare . If not defined , Compare two references .
public class ItemModelComparer : IEqualityComparer<ItemModel>
{
// Compare
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;
}
// Get the hash value
public int GetHashCode(ItemModel model)
{
if (Object.ReferenceEquals(model, null)) return 0;
int hashNurse = model.ItemCode.GetHashCode();
return hashNurse;
}
}
(3) The specific use is as follows
List<ItemModel> ListA = new List<ItemModel>();
List<ItemModel> ListB = new List<ItemModel>();
List<ItemModel> ListResult = new List<ItemModel>();
ListResult = ListA.Distinct(new ItemModelComparer()).ToList();// duplicate removal
ListResult = ListA.Except(ListB, new ItemModelComparer()).ToList();// Difference set
ListResult = ListA.Union(ListB, new ItemModelComparer()).ToList(); // Combine
ListResult = ListA.Intersect(ListB, new ItemModelComparer()).ToList();// intersection
2、 join Usage of
If there are two List, Want to use Linq The query . You can use the following method
int tempSatisfiedConditionCount = (from r1 in whiteList
join r2 in args.DiagList on r1.DiagCode equals r2.DiagCode
select r1).Count();
Multi conditional join
// Multi conditional joint audit
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>();
in addition ,join It can also be used for left connection / The right connection
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 usage
let It's a linq Define local variables in
1、 There can be multiple let Clause
2、let The variable after does not need to declare a type
See the following example :
var query = from a in list
let b = a.Name.Split('-')
let c=a.Age
where b[0] =="zhangs" & c>21
select a;
4、 grouping
Common grouping usage :
var linqtest = from r in db.Am_recProScheme
orderby r.rpId descending
group r by r.recType into n
select new
{
n.Key, // This Key yes recType
rpId = n.Sum(r => r.rpId), // Within the group rpId The sum of the
MaxRpId = n.Max(r => r.rpId),// The largest in the group rpId
MinRpId = n.Min(r => r.rpId), // The smallest in the group rpId
};
A little more complicated :
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>();
5、 Simple function calculation
var linqtest = (from r in db.Am_recProScheme
select r).Sum(p => p.rpId);
6、 Sort order by desc/asc
var linqtest = (from r in db.Am_recProScheme
where r.rpId > 10
orderby r.rpId descending // In reverse order
// orderby r.rpId, r.rpname descending // The reverse order of multiple conditions ( And SQL Statement )
// orderby r.rpId ascending // positive sequence
select r);
7、top(1)
// If you take the last one, you can arrange the values according to the flashback
var linqtest = (from r in db.Am_recProScheme
select r).FirstOrDefault();
8、 Skip the previous data and get the remaining data
var linqtest = (from r in db.Am_recProScheme
where r.rpId > 10
orderby r.rpId descending
select r).Skip(10).Take(10); // Take the first place 11 To the first article 20 Data
9、 contain
// have access to List、Array、string Of Contains() Method to judge
var linqtest = (from r in db.Am_recProScheme
where r.SortsText.Contains(" Zhang ")
select r);
10、 Link query
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、 Use linq Inquire about DataTable
// Traverse DataTable, Map the data to ClientStruct in :
List<ClientStruct> list = (from x in dtTable.AsEnumerable()
orderby x.Field<string>("") descending
where x.Field<string>("ErrorType") == " Leak "
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 Middle column row transfer operation (Aggregate Use )—2022-3-4
Solve the problem of grouping and aggregation .
The style of background data storage is :
Hope to achieve :
namely : Implement grouping , And can aggregate diagnostics ( Column turned )
linq Let's write it as follows :
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>();
Aggregate Specific description of , See Official website Aggregate Method statement
Reference resources : Zhanglonghao's blog in the blog park
边栏推荐
- September 17, 2020 gateway business process has two tasks: referer certification and non commodity Templating
- 2021 team programming ladder competition - Simulation Competition
- Recyclerview sticky (suspended) head
- Codeforces Round #645 (Div. 2)
- Codeforces Round #652 (Div. 2)
- Summary after the 2009 ICPC Shanghai regional competition
- Web vulnerability manual detection and analysis
- Weight recursion of complete binary tree -- the last programming challenge
- 520 diamond Championship 2021
- 2019.10.6 training summary
猜你喜欢
随机推荐
2019-11-10 training summary
這個開源項目超哇塞,手寫照片在線生成
Arc view and arc viewpager
2019.11.17训练总结
Rikka with cake (segment tree + segment tree)
这个开源项目超哇塞,手写照片在线生成
September 23, 2020 left and right values reference std:: move()
520 钻石争霸赛 2021
manacher
1099 Build A Binary Search Tree (30 分)
Summary after the 2009 ICPC Shanghai regional competition
基辅周边的凄美废墟——切尔诺贝利的安全前往指南!
Nacos环境隔离
2019.11.20 training summary
HDU 4578 transformation (segment tree + skillful lazy tag placement)
Application of Pgp in encryption technology
MySQL中update一条record的过程
Nacos registry cluster
单片机集成开发环境Keil5的使用
IIS服务器相关错误








