在两个列表中查找计数

时间:2012-10-26 15:52:37

标签: c# linq list foreach count

我从数据库中获得了两个列表,如下所示:

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和id1返回id = 1,从secondList ...返回id2

尝试了这个但没有工作

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

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

谢谢

1 个答案:

答案 0 :(得分: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;
    }
}