簡體   English   中英

在兩個列表中找到計數

[英]finding the count in two lists

我有兩個從數據庫中獲取的列表,如下所示:

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或normal foreach中幫助我嗎?

謝謝

看着這個問題,看來您想要確定哪個父節點具有最多的子節點,並且您希望輸出是該父節點及其所有子節點。

該查詢非常簡單:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM