Reputation: 5600
I have two lists which I am getting from database as follow:
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));
}
now my list will contain data like so:
frstList: id = 1, id = 2
secondList: id=1 parentid = 1, id=2 parentid=1 and id = 3 parentid = 2
I want to count these individually and return the one that has most counts? in above example it should return id=1 from frsList and id1 and id2 from secondList...
tried this but not working
var numbers = (from c in frstList where c.Parent.ID == secondList.Select(cl=> cl.ID) select c).Count();
can someone please help me either in linq or normal foreach to do this?
Thanks
Upvotes: 0
Views: 259
Reputation: 203819
Looking at the question it appears that what you want is to determine which of the parent nodes has the most children, and you want the output to be that parent node along with all of its child nodes.
The query is fairly straightforward:
var largestGroup = secondList.GroupBy(item => item.ParentID)
.MaxBy(group => group.Count());
var mostFrequentParent = largestGroup.Key;
var childrenOfMostFrequentParent = largestGroup.AsEnumerable();
We'll just need this helper function, 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;
}
}
Upvotes: 1