【问题标题】:finding the count in two lists在两个列表中查找计数
【发布时间】:2012-10-26 15:52:36
【问题描述】:

我有两个从数据库中获取的列表,如下所示:

List<myobject1> frstList = ClientManager.Get_FirstList( PostCode.Text, PhoneNumber.Text);
                List<myobject2> secondList = new List<myobject2>;

                foreach (var c in frstList )
                {
                    secondList.Add( ClaimManager.GetSecondList(c.ID));
                }

现在我的列表将包含如下数据:

frstList: id = 1, id = 2
secondList: id=1 parentid = 1, id=2 parentid=1 and id = 3 parentid = 2

我想单独计算这些并返回计数最多的那个?在上面的例子中,它应该从 frsList 返回 id=1,从 secondList 返回 id1 和 id2...

试过了,还是不行

var numbers = (from c in frstList where c.Parent.ID == secondList.Select(cl=> cl.ID) select c).Count();

有人可以在 linq 或普通的 foreach 中帮助我吗?

谢谢

【问题讨论】:

  • 我不确定我是否理解你的问题。您只是想返回包含最多项目的列表?
  • 您希望输出是什么样的?
  • 想要对 secondlist 进行计数并返回更大的计数...就像示例状态
  • 所以,只是更大的计数,而不是更大的列表?
  • 我不认为 foreach 循环中的语句是正确的。请检查一下。我同意 John 和 Lostdreamer 的观点,这个问题并不清楚。

标签: c# linq list foreach count


【解决方案1】:

查看问题,您似乎想要确定哪个父节点的子节点最多,并且您希望输出是该父节点及其所有子节点。

查询相当简单:

var largestGroup = secondList.GroupBy(item => item.ParentID)
  .MaxBy(group => group.Count());  

var mostFrequentParent = largestGroup.Key;
var childrenOfMostFrequentParent = largestGroup.AsEnumerable();

我们只需要这个辅助函数MaxBy

public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source
    , Func<TSource, TKey> selector
    , IComparer<TKey> comparer = null)
{
    if (comparer == null)
    {
        comparer = Comparer<TKey>.Default;
    }
    using (IEnumerator<TSource> iterator = source.GetEnumerator())
    {
        if (!iterator.MoveNext())
        {
            throw new ArgumentException("Source was empty");
        }

        TSource maxItem = iterator.Current;
        TKey maxValue = selector(maxItem);

        while (iterator.MoveNext())
        {
            TKey nextValue = selector(iterator.Current);
            if (comparer.Compare(nextValue, maxValue) > 0)
            {
                maxValue = nextValue;
                maxItem = iterator.Current;
            }
        }
        return maxItem;
    }
}

【讨论】:

  • 这有点像父母和孩子,我想找到孩子最多的父母......如果这有意义的话
  • @Sam1 根据输出值,这就是我猜你想要的。这符合您的要求吗?
  • 我将助手放在名为 helper 的单独类中,但在 maxby 扩展方法上出现错误
  • @Sam1 需要在静态类中;这就是扩展方法的工作原理。另请注意,一般来说,在此类网站上报告问题时,您应该提供错误消息;我通常无法读懂你的想法来知道你做错了什么。
  • 很抱歉,现在知道了...您介意解释一下辅助方法的作用吗,因为我是新手...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2022-11-13
  • 2021-05-10
  • 2011-01-25
相关资源
最近更新 更多