我需要能够从 ASP.NET DropDownList
中搜索单个名称,然后将具有该名称的播放器
添加到列表中。
我的查询如下所示:
List<Player> players = new List<Player>();
var p1 = from p in db.Players
where p.PlayerName == DropDownListPlayer1.SelectedItem.Text
select p;
然后,我需要将此结果添加到列表中,但是
players.Add(p1);
给了我两个错误:
Cannot convert from 'System.Linq.IQueryable' to 'Player,'
并且:
the best overloaded method match for 'System.Collections.Generic.List.Add(Player)' has some invalid arguments.
我尝试让查询选择一个新的 Player 实例:
var p1 = from p in db.Players
where p.PlayerName == DropDownListPlayer1.SelectedItem.Text
select new Player {PlayerName = p.PlayerName,
PlayerId = p.PlayerId};
以及将结果发送到列表,并将列表中的第一个(也是唯一一个)玩家添加到新列表中,所有这些都无济于事。
最佳答案
您正在寻找单个名称,但是 Select
返回一个序列( IQueryable<Player>
),您应该调用 First
或Single
添加到结果列表之前的查询:
var p1 = (from p in db.Players
where p.PlayerName == DropDownListPlayer1.SelectedItem.Text
select p).First();
players.Add(p1);
关于c# - 将单个查询结果添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102742/