Click here to Skip to main content
15,885,869 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have one model
MaterialModel

ID Material
1 MaterialZZZ
2 MaterialYYY
3 MaterialXXX
1 MaterialABC
2 MaterialKKK
2 MaterialVVV
5 MaterialMMM

Expected Result (Result Model)
ID Count
1 2
2 3
3 1
5 1
I want to group by and take the count and ID in linq lambda expression and that result to another List of Model. which has ID and Count properties

What I have tried:

int count = (from x in items select x).Count();

but i need group by and count in another list of model.

Thanks in advance.
Posted
Updated 14-Mar-22 10:48am

static void Main(string[] args) {
    List<Item> items=new List<Item>();
    items.Add(new Item(1, "zzz"));
    items.Add(new Item(2, "yyy"));
    items.Add(new Item(3, "xxx"));
    items.Add(new Item(1, "abc"));
    items.Add(new Item(2, "kkk"));
    items.Add(new Item(2, "bbb"));
    items.Add(new Item(5, "mmm"));
    var counters = from r in items
                  group r by r.ID into grp
                  select new { key = grp.Key, cnt = grp.Count() };
    foreach (var counter in counters) {
        Console.WriteLine("key=" + counter.key + ", count=" + counter.cnt);
    }

or
...
	var counters = items.GroupBy(r => r.ID)
		.Select(group => new { key = group.Key, cnt = group.Count() });
...


both with
public class Item {
    public int ID { get; set; }
    public string Material { get; set; }
    public Item(int ID, string material) {
        this.ID = ID;
        this.Material = material;
    }
}
 
Share this answer
 
v3
Take a look at below code:
void Main()
{
	List<MaterialModel> mm = new List<MaterialModel>()
	{
		new MaterialModel(){ID = 1, Material = "MaterialZZZ"},
		new MaterialModel(){ID = 2, Material = "MaterialYYY"},
		new MaterialModel(){ID = 3, Material = "MaterialXXX"},
		new MaterialModel(){ID = 1, Material = "MaterialABC"},
		new MaterialModel(){ID = 2, Material = "MaterialKKK"},
		new MaterialModel(){ID = 2, Material = "MaterialVVV"},
		new MaterialModel(){ID = 5, Material = "MaterialMMM"}	
	};

	List<ResultModel> rm = mm.GroupBy(x => x.ID)
		.Select(grp => new ResultModel()
		{
			ID = grp.Key,
			Count = grp.Count()
		})
		.ToList();
	rm.Dump();
}

// Define other methods and classes here
public class MaterialModel
{
	public int ID { get; set; }	
	public string Material { get; set; }
}

public class ResultModel
{
	public int ID { get; set; }
	public int Count { get; set; }
}


Next time, i'd suggest to read MSDN documentation first:
Group query results (LINQ in C#) | Microsoft Docs[^]
Enumerable.GroupBy Method (System.Linq) | Microsoft Docs[^]
101 LINQ samples - Code Samples | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900