【问题标题】:Get count of same value on table获取表上相同值的计数
【发布时间】:2021-08-24 20:29:40
【问题描述】:

我有这个类,查询必须在这个列表中产生一个属性。 此属性必须在表上检查存在多少重复项。 此代码有效,但速度很慢。你能帮我吗?

var lst = _uow.Repository.GetAll();
var query =
    from p in lst
    select new GetRfqResponse
    {
        ID = p.ID,

        //bad performance
            Count = lst.Where(x => x.Property == p.Property).AsQueryable().Count(),
        //
    };

【问题讨论】:

  • 我不认为lst.Where(p => p.Property == p.Property) 是对的。

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


【解决方案1】:

使用Count() 函数可以轻松实现在可查询列表中的计数:

// Find duplicated names
var byName = from s in studentList
             group s by s.StudentName into g
             select new { Name = g.Key, Count = g.Count() };

检查this fiddle 以查看它正在运行。

【讨论】:

    【解决方案2】:

    下面是 InMemory

    GroupBy 应该来帮忙。

    var propertyGroupedList = list.GroupBy(l=>l.Property);
    var query = list.Select(l => new GetRfqResponse{
              Id = l.Id,
              Count = propertyGroupedList.First(g=> g.Key == l.Property).Count()
    });
    

    或者您可以创建一个字典,其中键为“属性”,值为计数,然后您只需循环一次即可存储计数。 这使您可以在恒定时间内获得计数

    Dictionary<string, int> map = new Dictionary<string, int>();
    foreach (var item in lst)
    {
        if (!map.ContainsKey(lst.Property))
        {
            map.Add(item.Property, 1);
        }
        else
            map[item.Property]++;
    }
    
    var z = lst.Select(l => new GetRfqResponse{
        Id = l.ID,
        Count = map[l.Property]
    });
    

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2019-09-17
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多