C# 基础 - linq 举例应用

public class Player
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public bool IsPlaying { get; set; }
}


List<Player> playerList = new List<Player>()
{
    new Player() {Id = "1", Name = "姚明", Age = 41, IsPlaying = false},
    new Player() {Id = "2", Name = "刘玉栋", Age = 50, IsPlaying = false},
    new Player() {Id = "3", Name = "王治郅", Age = 44, IsPlaying = false},
    new Player() {Id = "4", Name = "易建联", Age = 34, IsPlaying = true},
    new Player() {Id = "5", Name = "万圣伟", Age = 27, IsPlaying = true},
};

1. linq 实现排序

如果想按照未退役在前,退役在后、年龄大在前,年龄小在后的顺序展示这 5 位运动员,可用下面两种的任一种实现:

playerList = playerList.OrderByDescending(p => p.IsPlaying).ThenByDescending(p => p.Age).ToList();

playerList = (from p in playerList orderby p.IsPlaying descending, p.Age descending select p).ToList();

2. First 和 FirstOrDefault

IEnumerable<Player> bidIdPlayers = playerList.Where(p => p.Age > 60);

Player playerA = bidIdPlayers.First(); // bidIdPlayers 为空的话报错,提示序列不包含任何元素
Player playerB = bidIdPlayers.FirstOrDefault(); // bidIdPlayers 为空的话不报错,playerB 值为 null

string idA = bidIdPlayers.FirstOrDefault().Id; // bidIdPlayers 为空的话报错,提示未将对象引用设置到对象的实例
string idB = bidIdPlayers.FirstOrDefault()?.Id; // bidIdPlayers 为空不报错,idB 值为 null
var age = bidIdPlayers.FirstOrDefault()?.Age; // bidIdPlayers 为空不报错, age 值为 null

posted @ 2021-03-03 20:21  鑫茂  阅读(57)  评论(0编辑  收藏  举报