【问题标题】:Load distinct values from database into List<>将不同的值从数据库加载到 List<>
【发布时间】:2013-05-21 21:06:49
【问题描述】:

我使用事件的外键创建了一个 Record POCO 类(=运动学科)。 一个记录可以链接到 1 个事件,但一个事件可以有多个记录(世界记录、奥林匹克记录等)。 现在我想使用 for-each 循环将数据库中的每个事件(+附加记录)打印到索引视图。

但是因为表 Record 没有 List 属性,我必须从我的 Record 表中创建一个本地(不同)事件列表,这就是我的问题。

更多信息,这里是我的 Record 模型

    public class Record
{
    [Key]
    public int RecordId { get; set; }
    public string ResultName { get; set; }
    public int ResultAge { get; set; }
    public double ResultPrestation { get; set; }
    public System.DateTime ResultDate { get; set; }
    public string ResultPlace { get; set; }
    public int CountryId { get; set; }  
    [ForeignKey("CountryId")]
    public virtual Country Country {get; set;}
    public int EventId { get; set; }
    [ForeignKey("EventId")]
    public virtual Event Event { get; set; }
}

以及事件模型

    public class Event
{
    [Key]
    public int EventId { get; set; }
    public String Sport { get; set; }
    public String Discipline { get; set; }
    public Boolean SchoolcupEvent { get; set; }
    public List<Record> Records { get; set; }
}

我写了一篇小文章,最后得到了一个记录存在的女巫的事件列表,但这不是一个独特的列表,这就是我需要的。

        List<Event> events = new List<Event>();
        foreach(var item in db.Records)
        {               
            Event e = db.Events.Find(item.EventId);
            events.Add(e);
        }

我希望有人可以帮助我。

问候

【问题讨论】:

    标签: c# database entity-framework list foreach


    【解决方案1】:
    var events = db.Records.Distinct().ToList();
    

    【讨论】:

      【解决方案2】:

      Enumerable.Distinct 应该可以工作

      【讨论】:

        【解决方案3】:

        如何将事件放入 Set 中,这将删除重复项(如果有),然后将 set 转换回列表。

        Set<Event> eventSet = new TreeSet<Event>();
        foreach(var item in db.Records)
        {               
                Event e = db.Events.Find(item.EventId);
                eventSet.Add(e);
        }
        List<Event> eventList = new ArrayList<Event>();
        if(eventSet != null && eventSet.size() > 0)
        {
                eventList.add(eventSet);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-20
          • 2011-07-25
          • 2012-09-15
          • 1970-01-01
          • 2015-07-16
          相关资源
          最近更新 更多