0

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

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 中帮助我吗?

谢谢

4

1 回答 1

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;
    }
}
于 2012-10-26T16:06:43.423 回答