Am I required to use a repeat loop if my LINQ query returns only one object?

Asked

Viewed 89 times

1

My class:

public class Carros {
    public int ID { get; private set; }
    public string Atributo2 { get; private set; }
    public int Atributo3 { get; private set; }}}

Suppose the ID attribute could not repeat itself and I created a Collection of the type of that class and wanted to return from that Collection only the car that had ID == 2

Then I would:

var carroId2 = from carro in collectionCarros
                       where carro.ID == 2
                       select new {
                           Id = carro.ID
                       };

And I wish I could do something like carroId2.ID to return the value of the attribute, but I can only do this within a loop ? Or is there another way I can do this.

1 answer

2


No. If you want to continue doing so and so still received a IEnumerable, has to access an element, can not access the direct object because it is a data collection object and wants the individual object.:

carroId2[0].ID

So the variable name couldn’t even be this (the variable carro also wrong, the class name is also because there is only one car and it makes no sense to be in plural), you have cars There, which you happen to know has only one, but it’s a very small collection of cars. If you want to take the individual object (I used its variable even though the name is conceptually wrong)

But you can take only object:

carroId2.FirstOrDefault().ID

The ideal is to check if the object is null because it can find no element, almost the same would have to be done by the data collection (only it would be enough to see if the collection is empty). If you are absolutely sure that you can’t see zero objects (I wouldn’t have so much) you can use the First(), if you find nothing you will have an exception, because it would be an unexpected mistake.

If you want to catch the whole object can do direct:

carro.FirstOrDefault(carro.ID == 2)

And you can only get the direct ID:

carro.FirstOrDefault(carro.ID == 2).ID

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.