简体   繁体   中英

ASP.NET MVC 4 get value from IQueryable

I have this variable here: var value = service.Get(UserId) this returns data from an IQueryable and has results. I am looking to grab the language from the results in the screenshot below, how would I do that? I tried value[0].language but that did not work :(

Any suggestions would be helpful:

在此处输入图片说明

I am looking to get the language value of "english" Please help.

I tried: string value = service.Get(UserId).FirstOrDefault().Language;

I am getting an error 'System.Linq.IQueryable' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Linq.IQueryable could be found (are you missing a using directive or an assembly reference?)'

Here is what I am using:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using CTHRC.Roti.Domain.Model;
using CTHRC.Roti.Domain.Api.Services;
using CTHRC.Roti.Domain.Data.Repositories;
using CTHRC.Roti.Data.EntityFramework.Repositories;
using CTHRC.Roti.Data.EntityFramework;

IQueryables are slightly different than plain arrays. In order to see the results view, you had to enumerate the IQueryable. You can actually see that in your screen shot where it says "Expanding the Results View will enumerate the IEnumerable". This quote is the key to this scenario. If the IEnumerable is not enumerated, then no actual data is brought from the database. There are various ways in code to enumerate the IEnumerable such as using .ToList, .Select, .Single, .First, and a few others.

I believe you will be interesting in using .FirstOrDefault() . The "OrDefault" part just means if the list is empty no exception is thrown. This may or may not be desirable depending on the scenario.

string language = service.Get(UserId).FirstOrDefault().Language;

in order to avoid an exception if there are no users returned, a projection could be first used.

string language = service.Get(UserId).Select(u => u.Language).FirstOrDefault();

which will produce null if there were no users.

尝试如下所示的Cast()

 string Language= service.Get(UserId).Cast<Users>().FirstOrDefault().Language;

Several options, in your code value is a list of items not a value.

string xyz = value[0].Language;

or

Just get a single item

var item = service.Get(UserId).FirstOrDefault();
string xyz = item.Language;

if not strongly typed string xyz = item["Language"];

I concur with sywester's answer but with a little tweak. You have to check for null first or you'll introduce a null bug into your system. So

var a = service.Get(UserId).FirstOrDefault(); string Language = a!=null? a.Language : string.Empty;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM