C# 列表中的第一个方法

C# 列表中的第一个方法,c#,list,C#,List,我有这门课: public class Game { public string Name { get; set; } public int Players{ get; set; } public int ReleaseYear{ get; set; } } 我想创建一个列表 List<Game> list = new List<Game>(); 但是程序什么也没做,却没有抛出任何异常,这有什么问题吗?您填充了列表吗?试试这个: var gam

我有这门课:

public class Game
{
    public string Name { get; set; }
    public int Players{ get; set; }
    public int ReleaseYear{ get; set; }
}
我想创建一个列表

List<Game> list = new List<Game>();

但是程序什么也没做,却没有抛出任何异常,这有什么问题吗?

您填充了列表吗?试试这个:

var games = new List<Game> {
                new Game { Name = "Foo Bros.", Players = 2, ReleaseYear = 1983 },
                new Game { Name = "Hope", Players = 4, ReleaseYear = 1993 }
            };
var firstFourPlayerGame = games.First(g => g.Players == 4);
Console.WriteLine(firstFourPlayerGame.Name);
var games=新列表{
新游戏{Name=“Foo Bros.”,玩家=2,发布年份=1983},
新游戏{Name=“Hope”,玩家=4,发布年份=1993}
};
var firstFourPlayerGame=games.First(g=>g.Players==4);
Console.WriteLine(firstFourPlayerGame.Name);
输出:


希望它能运行,因为列表是空的,如果您不使用FirstOrDefault,并且没有玩家=2的项目,它也会运行。

如果它有帮助,这会起作用

        List<Game> list = new List<Game>();
        list.Add(new Game() { Players = 2, Name = "Football" });
        list.Add(new Game() { Players = 1 });
        list.Add(new Game() { Players = 2, Name = "Soccer" });

        Game g = list.First<Game>(k => k.Players == 2);
        //g will contain the "Football" game
List List=新列表();
添加(新游戏(){Players=2,Name=“Football”});
添加(新游戏(){Players=1});
添加(新游戏(){Players=2,Name=“Soccer”});
游戏g=列表。首先(k=>k.玩家==2);
//g将包含“足球”游戏

您所说的“它什么都不做”是什么意思?行执行后g的值是多少?如果列表是一个“列表”,那么
First()
的结果将是
游戏的一个实例。你在检查“g”对象吗?其中应该有选定的元素。另外,最好使用list.First(k=>k.Players==2)来避免强制执行。@cornerback84:您不需要显式地将类型参数声明为
First
;编译器将从
list
@blur的类型推断出它,这可能更安全,因为在生产中,如果列表不包含任何满足条件的元素,则不会崩溃
        List<Game> list = new List<Game>();
        list.Add(new Game() { Players = 2, Name = "Football" });
        list.Add(new Game() { Players = 1 });
        list.Add(new Game() { Players = 2, Name = "Soccer" });

        Game g = list.First<Game>(k => k.Players == 2);
        //g will contain the "Football" game