Fox
Fox

Reputation: 891

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

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;    
    }

Upvotes: 0

Views: 493

Answers (4)

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

Upvotes: 3

Somnath
Somnath

Reputation: 3275

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 } );

Upvotes: 1

Teudimundo
Teudimundo

Reputation: 2670

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.

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54646

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?

Upvotes: 1

Related Questions