【问题标题】:Asp.Net duplicates from database数据库中的 Asp.Net 重复项
【发布时间】:2018-04-18 12:13:41
【问题描述】:

有一个表格,其中包含新闻和类别 ID(多对多)。我想推断没有重复的新闻,但 Distinct 方法没有帮助。如何解决问题?

ViewBag.NewsToCategory = db.News_To_Category.Where(db=>db.News.Status == 1).Distinct().ToList();

HTML 代码

@foreach(News_To_Category nw in ViewBag.NewsToCategory)
    {
        <div class="col-md-4 col-sm-4 hidden-sm">
            <div class="blog-home blog-box">
                <div class="blog-top-desc">
                    <div class="blog-date">
                        @Convert.ToDateTime(nw.News.Dates).ToString("dd MMMM yyyy")
                    </div>
                    <h4>@nw.News.Title</h4>
                    <i class="fa fa-user-o"></i>
                    <strong>admin</strong>
                    <i class="fa fa-commenting-o"></i>
                    <strong>8 comments</strong>
                </div>
                <img style="min-width:370px;max-width:370px;min-height:240px;max-height:240px" src="~/Uploads/@nw.News.Image">
                <div class="blog-btm-desc">
                    <p>
                        @nw.News.Content;
                    </p>
                    <a href="#" class="btn btn-min btn-solid">
                        Read More
                        <i class="fa fa-arrow-right"></i>
                    </a>
                </div>
            </div>
        </div>
    }

【问题讨论】:

  • 在News_To_Category表中,有几行具有相同的新闻ID附加到不同的类别,我想只打印该表的新闻,但没有重复,但相同的新闻显示了多次, 不包括 dictinct (), 如何禁用新闻输出
  • 不能在 where 子句中包含NewsCategory 吗?

标签: asp.net asp.net-mvc-4 distinct viewbag actionresult


【解决方案1】:

类似的东西。过滤状态 = 1 并按日期降序排列。按 Id 分组以获取重复项,然后选择每个组中的第一个。

ViewBag.NewsToCategory = db.News_To_Category.Where(db=>db.News.Status == 1).OrderByDescending(x => x.News.Dates)).GroupBy(x => x.News.Id).Select(x => x.News.FirstOrDefault()).ToList();

【讨论】:

  • 对不起朋友,但是 GROPBY() "当前内容中不存在"((
  • @Самир Гасанов 你是不是用“u”这样拼写的。 GroupBy 是 Linq 库中 IEnumerable> 的扩展方法。从你的代码和你所说的我可以看出,你正在使用 Linq to SQL 在一个绝对有 GroupBy 的 DbSet 上。
  • @СамирГасанов 你能让这个解决方案发挥作用吗?
猜你喜欢
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 2013-01-18
  • 2016-01-12
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多