score:2
I would use the linq .Count() extension, which will count the number of items that satisfy a condition. Yes, this will iterate the list more times than is necessary, but it doesn't create any unnecessary objects, and it is very readable:
var countOccurences = new List<int>();
foreach (var inA in listA)
{
countOccurences.Add(listB.Count(inB => inB == inA));
}
Console.WriteLine(string.Join(", ", countOccurences));
Once you've got the loop working, then it should be easy to see that it can be done in a single statement:
var countOccurences = listA.Select(inA => listB.Count(inB => inA == inB));
score:0
It's a good problem to use left outer join in LINQ. Here is an article about it. It's the best performance solution because you iterate over the collection just once and it's important for big collections or frequently used methods.
Here is an example for your problem:
var result = from a in listA
join b in listB.GroupBy(x => x) on a equals b.Key into gj
from subList in gj.DefaultIfEmpty()
select new
{
Number = a,
Count = subList?.Count() ?? 0
};
You can also use GroupJoin and method chaining but I think that it's much harder to read:
var result = listA
.GroupJoin(listB.GroupBy(x => x), a => a, b => b.Key, (a, gj) => new { a, gj })
.SelectMany(@t => @t.gj.DefaultIfEmpty(), (@t, subList) => new { Number = @t.a, Count = subList?.Count() ?? 0 });
After that result will contains a collection of anonymous types with fields Number
and Count
with 3 elements: {1, 3}, {2, 4}, {8, 0}
.
Update from comments (thanks to Caius Jard): if you can't use Null-Conditional Operator you may just replace it with explicit check: subList == null ? 0 : subList.Count()
score:0
fixing your code
var result = listB.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count());
foreach(var ent in listA)
Console.WriteLine(result.ContainsKey(ent)?result[ent]:0);
score:0
one line Linq statment
listA.Select(a => listB.Contains(a) ? a : 0 ).Select(r=>listB.Count(w=> w==r)).ToList();
Source: stackoverflow.com
Related Articles
- How to count the occurence of each number in list A that is exist in list B and return zero if not existed?
- I want to count number of each element in list using linq in c#
- Count how many times a number appeared within a range of that list
- How to count the number of elements that match a condition with LINQ
- Linq selecting items that exist in both list
- How to count the number of code lines in a C# solution, without comments and empty lines, and other redundant stuff, etc?
- LINQ Lambda - Find all ID's in one list that don't exist in another list
- Count number of given object in a list with LINQ
- In a C# List how to select all columns + several custom columns, so that in each row all columns are flat (not nested)?
- Calculating the sum of the values in a dictionary that exist in a generic list
- How to group and count the number of occurence of item in comma delimited string
- How can I count number of objects in a list with a unique property with linq/lambda?
- Using LINQ I have a list of lists, how do I select all objects that exist in every list?
- c# Group a list and get the count of each group
- Get items from input list that do not exist in the database using EF Core 2.1
- Excluding items from a list that exist in another list
- Count the number of element present in the inner list
- Count the number of Enum values in list using Linq
- How do I count a number of items in each group in sequence using linq?
- Linq for selecting elements from list 1 that exist on list 2 by comparsion between 2 properties values
- Using ASP.NET and MVC 3, how can I create hidden fields so that a List with an array as a value of each item in the list binds correctly?
- Linq to entities query that returns a count and a list of objects
- How do I get a list of integers that exist in one collection, but not in another of a different type using LINQ?
- How can I flatten out data in a list and then get a count of what's in each column using LINQ?
- how to find items in list that their sum is less than or equal a number
- Given collection of strings, count number of times each word appears in List<T>
- Is there a C# function that checks if a list is empty and doesn't count null as an element?
- How get count of each distinct item in generic List in C#
- Filter a List<T> based on another list that each instance of T contains
- Select all from one List, replace values that exist on another List
- This is my SQL query that is used to retrieve the sum of quantity where product has same id, I want to use it in LINQ
- Information saved in memory when using pending request in LINQ
- C# Linq All Condition
- Wrong results for suming right side of List
- How to filter a flattened LINQ result in C#
- How to use linq include function in generic type
- How to combine multiple lists using LINQ lambda
- Compiled LINQ query & DataLoadOptions... with a twist!
- Is there any benefit to calling .Any() before .ForEach() when using linq?
- EFCore + Linq, how to Select specify users first, then rest of them?
- Access multiple database using linq in asp.net
- DataTable Trickle down duplicate values to last duplicate to fill with most recent data
- An un-representable DateTime for year, Month and Day parameters in C#
- .NET - ORMs and all possible combinations - ViewModel?
- Entity framework is generating SQL that returns the entire table
- Linq query to SQL query
- C# multiple joins and not existing in another table
- XDocument.Descendants returning null values
- Two different queries - Returning inconsistent results
- Linq - Select surrounding objects between two others