I have 3 tables in my database:

  1. Categories: ID(PK), CreationDate
  2. Languages: ID(PK), Title
  3. CategoryDetails: ID(PK), CategoryID(FK), LanguageID(FK), Title, Description

I've also created a ViewModel in MVC 4 with all the tables, but when I'm trying to list the Category Details in the view (.cshtml), the WHERE clause doesn't work as I was expected. I'm trying to list the Language not by key, but by Title.

@foreach (var item in Model.lstCategoryDetails)
    {
        <tr>
            <td>@item.Title</td>
            <td>@Model.lstLanguages.Title.Where(x => x.ID == @item.LanguageID)</td>
            <td>@item.Description</td>
        </tr>    
    } 
有帮助吗?

解决方案

  • Enumerable.Where returns another IEnumerable, even if this contains just one found item. So replace .Where( with .FirstOrDefault( or .Single( etc.
  • You also don't need the additional @ on in the lambda filter.
  • Once you've done this, access the Title property of the selected Language

e.g.

@Model.lstLanguages.FirstOrDefault(x => x.ID == item.LanguageID).Title

Note that you'll get a NRE if the language isn't found.

其他提示

you should say

@Model.lstLanguages.Where(x => x.ID == @item.LanguageID).First().Title

you can apply 'where,select etc...' to list, and return type is Ienumerator.

when you apply 'First() or FirstOrDefault()' returns to you element type of your list.

for exm. you have List<int> intList = (1,2,3,4,5,6).

and applying:

intList.where(p=>p == 4 || p== 5).FirstOrDefault();

returns to you '4' as type of integer.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top