使用Linq C#从连接的两个列表中获取第一个列表的计数#

时间:2017-09-15 06:45:25

标签: c# linq

我有以下代码连接两个列表。

public List<Summary> GetSummary()
{
    List<Summary> summ = new List<Summary>();
    summ = (
        from xyz in (
            from list1 in GetList1()
            join list2 in GetList2() on list1.ID equals list2.ID
            select new { list1, list2 }
            )
        group xyz by new { xyz.list1.ID } into g
        select new Summary
        {
            ID = g.Key.ID,
            ItemCount = g.Sum(x => 1), //getting wrong count //g.Count() is also not working.
            Quantity = g.Sum(x => x.list1.Quantity),
            Weight = g.Sum(x => x.list2.Weight),
            Time = TimeSpan.FromHours(Convert.ToDouble(g.Sum(x => x.list1.Time))).ToString(@"dd\.hh\:mm\:ss"),
        }
            ).ToList();
    return summ;
}

我想得到第一个列表(List1)的计数,但我得错了计数(以倍数表示)。例如。如果项目计数为6,那么我得到结果为36。

2 个答案:

答案 0 :(得分:1)

你能试试吗?我刚刚在ID属性上使用了GroupJoin,并使用了与你相同的逻辑。

var summ = GetList1().GroupJoin(GetList2(), l1 => l1.ID, l2 => l2.ID, 
            (l, g) => new Summary 
            { 
                ID = l.ID, 
                ItemCount = g.Count(), 
                Quantity = l.Quantity,
                Weight = g.Sum(x => x.Weight),
                Time = TimeSpan.FromHours(Convert.ToDouble(g.Sum(x => x.Time))).ToString(@"dd\.hh\:mm\:ss"),
            }).ToList();

答案 1 :(得分:1)

我重新编写了查询。试试以下。首先加入集合并获取所需的项目。然后,您可以执行该组以防止重复。

 public List<Summary> GetSummary()
        {
            List<Summary> summ = new List<Summary>();
            summ = (
                        from list1 in GetList1()
                        join list2 in GetList2() on list1.ID equals list2.ID
                        select new
                        {
                            ID = list1.ID,
                            Quantity = list1.Quantity,
                            Weight = list2.Weight,
                            Time = list1.Time
                        }
                        into list
                        group list by new { list.ID } into g
                        select new Summary
                        {
                            ID = g.Key.ID,
                            ItemCount = g.Count(),
                            Quantity = g.Sum(x => x.Quantity),
                            Weight = g.Sum(x => x.Weight),
                            Time = TimeSpan.FromHours(Convert.ToDouble(g.Sum(x => x.Time))).ToString(@"dd\.hh\:mm\:ss"),
                        }
                      ).ToList();

            return summ;
        }
相关问题