开发者

How to know if linq returned an object?

开发者 https://www.devze.com 2023-02-01 09:01 出处:网络
for example. I have a linq query to search a customer var customer = from c in _repo where c.username == username

for example.

I have a linq query to search a customer

var customer = from c in _repo
               where c.username == username
               select c;

How to tell if customer is found?

I've tried

if(customer)

But VS says can't implicitly convert typ开发者_运维知识库e Models.Customer to bool

The model is generated by EF4.

Since used repository pattern.

The single method returns public TEntity Single(Expression> predicate)


It looks like you're really trying to find a single customer, so use:

var customer = _repo.SingleOrDefault(c => c.username == username);
if (customer != null)
{
    ...
}

If there might be multiple customers with the same name, you should consider whether you want to find all of them, or whether you can just use the first one. If you can give more details about what you're trying to do, we can help more.


You can use Enumerable.Any:

if (customer.Any())
0

精彩评论

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