A Journal Through My Activities, Thoughts, and Notes
#csharp #linq

LINQ supports multiple fields in OrderBy, just like SQL's ORDER BY A DESC, B ASC.

---

### Example: Equivalent of ORDER BY A DESC, B ASC in LINQ

var sorted = data
.OrderByDescending(x => x.A)
.ThenBy(x => x.B);


---

### Explanation:

- OrderBy / OrderByDescending sets the primary sort.
- ThenBy / ThenByDescending adds secondary, tertiary, etc., sorts.

Each ThenBy applies only if the previous key values are equal—just like in SQL.
#linq #csharp

以下方法可以安全地从一个可能为空的集合中获取最大值,并在集合为空时返回一个默认值。代码如下:

var maxValue = aList.Select(a => a.aIntField).DefaultIfEmpty(0).Max();


### 解释:
- Select(a => a.aIntField): 选择每个对象的 aIntField 字段。
- DefaultIfEmpty(0): 如果 aList 为空,返回一个包含 0 的集合。
- Max(): 计算最大值。

这样,如果 aList 为空,maxValue 将会是 0,避免了抛出异常的风险。
 
 
Back to Top