常见Linq表达式的示例 [英] Examples of Common Linq Expressions
问题描述
在编写代码时,我开始确定可以使用Linq的那些地方.我的问题是我对语法还是很陌生.我通过示例学习得最好,但是似乎无法轻松找到所需的示例.
When I'm writing code, I'm starting to identify those places where I could use Linq. My problem is that I'm still very new to the syntax. I learn best through examples, but I can't seem to easily find the example I need.
我想启动此线程来创建一个常见的Linq表达式的存储库,其他人可能会通过Google偶然发现它们.
I wanted to start this thread to create a repository of common Linq expressions that others could stumble upon via google.
问题:您能否提供用于常见任务的Linq表达式的任何示例?
The question: can you provide any examples of Linq expressions you use for common tasks?
例如,我已经写了以下内容:
For example, I've already written the following:
- 搜索列表
- 求和数组
- 对元素集合中的某个属性求和
要启动线程,我将发布包含这些内容的答案.
To get the thread started, I'll post an answer that contains these.
推荐答案
枚举列表以查找特定元素
Enumerating through a list to find a certain element
tboShippingLotNumber existingLotNumber =
(tboShippingLotNumber)(from lot in shipmentDetailLine.LotNumbers
where
(lot.LotNumber == lotNumber) &&
(lot.ShipLineKey == shipmentDetailLine.Key)
select lot).ElementAtOrDefault(0);
if (existingLotNumber == null)
{
// not found exception
}
对数组求和:
decimal[] array = { 1.5m, 2.5m, 3.5m };
decimal sum = array.Sum();
总结对象列表中的某个属性
Summing a certain property in a list of objects
decimal sum = (from shipment in _ShipmentData.Shipments select
shipment.AmountShipped).Sum()
这篇关于常见Linq表达式的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!