当前位置:网站首页>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
边栏推荐
猜你喜欢

1146 Topological Order (25 分)

Sixteen system counter and flow lamp

Application of keil5 integrated development environment for single chip microcomputer

六度空间 bfs

IIS服务器相关错误

PGP在加密技术中的应用

Download control 1 of custom control (downloadview1)

The stones game

任务调度器之Azkaban的使用

SeaweedFS安全配置(Security Configuration)
随机推荐
Summary after the 2009 ICPC Shanghai regional competition
C#中IEqualityComparer接口的实现
Wandering --- 最后的编程挑战
时变和非时变
同花顺炒股软件可靠吗,安全吗?
通过Win32API调用另一界面的按钮
2019.10.23 training summary
山科 的C语言2018练习题(电信)
Reverse thinking - short story
Talk about threads and concurrency
F5 big IP Icontrol rest command execution (cve-2022-1388)
To 3 --- 最后的编程挑战
PGP在加密技术中的应用
Web vulnerability manual detection and analysis
单片机集成开发环境Keil5的使用
2019.10.27 training summary
L1-009 N个数求和 (20 分)
Arc view and arc viewpager
L2-025 分而治之 (25 分)
信号作品:时变和时不变