문제

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