简体   繁体   中英

How can I show just distinct names (from my model) in my view?

Problem

How can I return back just the distinct names in my view? I can't cast the string returned by my distinct() method back to an Inumerable object.

For simplification, if you see a person named John Smith in the database, we assume all quotes from John Smith are from the same person.

Code

Data

id                name          quote
1                 Finn          Mathematical
2                 Jake          Aw, man! 
3                 Shredder      Tonight, I dine on turtle soup. 
4                 Shredder      Nooooo

Model

    namespace Quotes_Sample.Models
{
    public class QuoteDB
    {

        public int Id { get; set; }
        public string name { get; set; }
        public string quote { get; set; }
        public bool IsSelected { get; set; }

    }


    public class QuoteDBContext : DbContext
    {
        public DbSet<QuoteDB> Quotes { get; set; }
    }


}

Controller

 private QuoteDBContext db = new QuoteDBContext();

    // GET: Quotes
    public ActionResult Index()
    {
        return View(db.Quotes.ToList());
    }

View

@model IEnumerable<Quotes_Sample.Models.QuoteDB>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @using (Html.BeginForm("SubmitSelected", "Quotes", FormMethod.Post, new { encType = "multipart/form-data", name="myform"}))
    {

        <table class="table">
            <tr>
                <th>
                   @Html.DisplayNameFor(model => model.name)
                </th>
            </tr>
            @foreach (var item in (IEnumerable<Quotes_Sample.Models.QuoteDB>)Model.Select(x => x.name).Distinct())
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.name)
                    </td>
                </tr>
            }
        </table>

    }

</body>
</html>

Error

An exception of type 'System.InvalidCastException' occurred in App_Web_cied5w21.dll but was not handled in user code
Additional information: Unable to cast object of type '<DistinctIterator>d__81`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[Quotes_Sample.Models.QuoteDB]'.

Attempts

  • I can just remove the casting and have duplicates, but it's really ugly.
  • I thought about writing a temp variable that remembers last name in loop, if same it breaks. That is just plain gross? Seems hacky too.
  • Just having 1 name to 1 quote relationship in my database, but that avoids the problem completely.
  • This , which actually brought me to this problem.
  • This below:

     <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.name) </th> </tr> @foreach (string name in Model.Select(x => x.name).Distinct()) { <tr> <td> @Html.DisplayText(name); </td> </tr> } </table> 

    But that really weirds me out. It gives me the following:

     name ; ; ; 

Thanks for your patience and assistance.

You can get Distinct records by name using:

Model.GroupBy(x => x.name).Select(x => x.First())

But you should do this in your Controller , not View .

Also you can use DistinctBy method:

Model.DistinctBy(x => x.name)

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