开发者

Linq Help please.. Direct casting to Object instead of Var

开发者 https://www.devze.com 2023-04-01 17:12 出处:网络
I\'ve always ignored the need for LINQ by iterating over objects but recently decided its time to leave behind the old school methods and get with the times.

I've always ignored the need for LINQ by iterating over objects but recently decided its time to leave behind the old school methods and get with the times.

I'm wondering if someone can help me simplify the below code by firstly, using Lambda instead of old school Linq and secondly, the below code will always return only 1 valu开发者_如何转开发e.. How can I cast directly to the correct type (Player) in this case without having to iterate again?

    MyEntities entity = new MyEntities();

    Guid selectedPlayerID = Guid.Parse(lbPlayers.SelectedItem.Value);


    var player = from n in entity.Players
                 where n.ID == selectedPlayerID
                 select n;

    foreach (var item in player)
    {
        tbPlayerSurname.Text = item.Name;
        tbPlayerName.Text = item.Surname;    
    }


If entity.Players contain Player objects you can simply specify

IEnumerable<Player> players = entity.Players
.Where(p => p.ID == selectedPlayerID); 

I was having trouble understanding your post so my initial answer was to actually select only one (and reading comments i see that is what you wanted) which you could do like this:

Player player = entity.Players.Single(p => p.ID == selectedPlayerID);

This throws and error if there are not excatly one, you could use SingleOrDefault and check for null, or even FirstOrNull, in which case you risk swallowing a potential error if there were more than one and that is supposed to get caught


var blahs = entity.Players.Where(x => x.ID == selectedPlayerID)
                  .Select(x => new blah() { Name = x.Name, Text = x.Surname);

This gives you an IEnumerable<Blah>.

Does it make sense?


You can use:

entity.Players.Single(n=>n.ID==selectedPlayerId);

if you think it might not exist use SingleOrDefault (and check the return value being different from default, null in case of classes). if you care only about the first one use First or FirstOrDefault instead.


Try this code below if **entity.Players is of type List<Player>

List<Player> selectedPlayers = (from n in entity.Players 
                                where n.ID == selectedPlayerID select n).ToList();

And if entity.Players is not of type List<Player>

List<Player> selectedPlayers = (from n in entity.Players 
                               where n.ID == selectedPlayerID 
                               select new Player() { Name = n.Name, Surname = n.Surname } );
0

精彩评论

暂无评论...
验证码 换一张
取 消