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 value.. 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
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:
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