2

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>    
    } 
Stiliyan Vasilev
  • 179
  • 2
  • 3
  • 14

2 Answers2

3
  • 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.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • It still doesn't work. I got an error: Compiler Error Message: CS1061: 'System.Collections.Generic.List' does not contain a definition for 'Title' and no extension method 'Title' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference – Stiliyan Vasilev Jan 30 '14 at 11:35
  • Updated - Title is a property on Language. – StuartLC Jan 30 '14 at 11:40
  • Oh, the mistake was in the syntax, It works now! Thanks a lot for the help Stuart :) – Stiliyan Vasilev Jan 30 '14 at 11:43
1

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.

mrTurkay
  • 642
  • 1
  • 7
  • 13