【问题标题】:How to get only distinct values from joined multiple tables如何从连接的多个表中仅获取不同的值
【发布时间】:2020-07-06 10:53:33
【问题描述】:

Here i want to show only distict values

var projects = (from dtid in db.Types.Where(dtid => dtid.Site == 1)
                    join diid in di on dtid.TypeId equals diid.TypeId
                    join dicid in dic on diid.DonationId equals dicid.DonationId
                    join eeid in ee.Where(eeid => eeid.IsActive == true) on dicid.ExEnId equals eeid.ExEnId
                    join cid in c on eeid.CoId equals cid.CoId
                    where dtid.DonationTypeId == id                             

                    select new Newmodel
                    {
                        countries = cid,
                        exEn = eeid,
                        donationItemCountries = dicid,
                        donation = diid,
                        types = dtid                               

                    }).Distinct().ToList().Take(100) ;

return View(projects);

我有一个包含一些相关数据的多表,我想使用 .NET 核心实体框架仅向视图显示唯一的国家/地区 这是代码。

型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace website.Models

{
    public class Newmodel
    {

        public Types types { get; set; }
        public Donation donation { get; set; }
        public DonationCountries donationCountries { get; set; }
        public ExEn exEn { get; set; }
        public Countries countries { get; set; }


    }
}

【问题讨论】:

  • 您想通过哪个属性比较您的对象?
  • 可以分享详细的模型吗?
  • @Rena 请检查我的模型有没有错误?
  • 嗨@MohamedAbubakkar,这只是一个视图模型。我认为您需要用简单的代码分享您的Types,Donation,DonationCountries,ExEnCountries 模型关系设计。

标签: c# asp.net .net asp.net-mvc asp.net-core


【解决方案1】:

通过什么进行比较?在没有和 IEqualityComparer 的情况下调用 Distinct() 与您通常使用 == 的效果相同,这意味着它看起来是否引用相等。我猜您想按国家/地区名称或国家/地区 ID 进行比较,这意味着您需要自定义 IEqualityComparer,幸运的是它们很容易实现:

class NewmodelEqualityComparer : IEqualityComparer<Newmodel>
{
    public bool Equals(Newmodel n1, Newmodel n2)
    {
        // Replace '.countries' with whatever property you want to compare
        return n1.countries == n2.countries;
    }

    public int GetHashCode(Newmodel n)
    {
        return n.GetHashCode()
    }
}

您对Distinct 的调用只需将其作为其相等比较器传递,如下所示:

.Distinct(new NewmodelEqualityComparer()).Take(100).ToList();

注意我是如何切换TakeToList 的位置的,这是因为如果你先ToList 然后Take 100 将处理整个底层原始列表,然后将取100。我们可以通过首先取 100 然后将底层集合转换为列表来提高效率,从而可能节省数千次对 Distinct 的调用。这是由于deferred execution 提供的IEnumerable 和LINQ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多