1

I'm currently learning C# .net and I'm attempting to display a distinct list of states, but I just can't figure out how to do this.

In my controller I have:

public ActionResult StateListDistinct()
        {
            var distinctStates = (from w in db.Contact_Addresses
                                  select new { State = w.Site_address_state}).Distinct();

            return View(distinctStates.ToList());
        }

And in my view I have:

@model List<String>
<table class="table">

@foreach (var item in Model) {
    <tr>

        <td>
            @Html.DisplayFor(model => item)
        </td>

    </tr>
}

</table>

I'm getting the error

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType1`1[System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[System.String]'.

What do I need to do to display a list of states?

1
  • select new w.Site_address_state assuming Site_address_state is of type string. Commented May 7, 2015 at 2:07

1 Answer 1

4

Your view is expecting a list of strings, but what you're feeding it is a list of anonymous types.

Using method syntax, what you're trying to achieve can be done this way:

db.Contact_Addresses.Select(state =>state.Site_address_state).Distinct().ToList();

This should do the trick as well:

var distinctStates = (from w in db.Contact_Addresses
                              select w.Site_address_state).Distinct().ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.