代码之家  ›  专栏  ›  技术社区  ›  Alex

在LINQ group by procedure之后访问列表<T>中保存的对象属性

  •  1
  • Alex  · 技术社区  · 16 年前

    我有一个 List<T> 它包含多个称为tc类型的对象 TwitterCollection . tc的每个实例包含5个属性。

    public class TwitterCollection
    {
        public string origURL { get; set; }
        public string txtDesc { get; set; }
        public string imgURL { get; set; }
        public string userName { get; set; }
        public string createdAt { get; set; }
    
    }
    

    我正在运行Linq to objects语句,如下所示:

        var counts = from tc in sList
                     group tc by tc.origURL into g
                     orderby g.Count()
                     select new { myLink = g.Key, Count = g.Count() };
    

    现在我的问题是,我无法访问任何 tc origURL 没问题,因为它是分配给 g txtDesc , imgURL 其他属性似乎无法访问。我需要上面的陈述,以便对我的数据进行适当排序。

    tc ,再加上仍按排序/排序 Count() 以现在的方式。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Jon Skeet    16 年前

    您已经对结果进行了分组-那么您希望获得哪个用户名?这个团体是一个整体 序列 元素,所有元素都具有相同的URL。如果要使用第一个,可以执行以下操作:

    var counts = from tc in sList
                 group tc by tc.origURL into g
                 orderby g.Count()
                 select new { myLink = g.Key, First = g.First(), Count = g.Count() };
    

    然后你可以做:

    foreach (var group in counts)
    {
        Console.WriteLine(group.First.userName);
    }
    

    如果您想要整个组,只需选择它:

    var counts = from tc in sList
                 group tc by tc.origURL into g
                 orderby g.Count()
                 select new { Group = g, Count = g.Count() };
    

    诚然,在这一点上,没有 Count 单独-您可以执行以下操作:

    var groups = sList.GroupBy(tc => tc.origURL)
                      .OrderBy(g => g.Count());
    

    foreach (var group in groups)
    {
        int count = group.Count();
        var key = group.Key;
        foreach (var entry in group)
        {
            // Use each item in the group, etc.
        }
    }
    
        2
  •  1
  •   jason    16 年前

    问题是您实际上已放弃了组中的所有项目。你需要以某种方式维护这些信息。例如:

    var groups = from tc in sList 
                 group tc by tc.origURL into g 
                 orderby g.Count() 
                 select new { myLink = g.Key, Items = g }; 
    
    foreach(var group in groups) {
        Console.WriteLine("Link: {0}, Count: {1}", group.myLink, group.Items.Count());
        foreach(var item in group.Items) {
            Console.WriteLine(item.txtDesc);
        }
    }
    
    推荐文章