Remove duplicates from EntityCollection - c#

I have an EntityCollection which contains members coming from different Marketing Lists. Because a person can exist in various MarketingLists my EntityCollection can contain the same person multiple times.
To have this data initially grouped I do the following:
var groupedCustomerList = listMembers.Entities.GroupBy(u => u.Id).Select(grp => grp.ToList());
My EntityCollection contains also an Attribute called "priority" which leads to the following if the same person is found multiple times
Group_1
- Person_1 (priority 1)
Group_2
- Person_1 (priority 2)
- Person_2 (priority 1)
What I need to achieve is to remove the duplicate person(s) with the lower priority -> Person_1 in Group_2 needs to be removed.
What I have tried so far is:
foreach (var item in groupedCustomerList)
{
if (item.Count > 1)
{
// order the items in the group by priority set in the SelectionRow and take the first
// entry with the highest priority
var element = item.OrderBy(o => o.Attributes[AttributeNames.SelectionRow.SelectionRowPriority]).Take(1).ToList();
listMembersConsolidated.Add(element[0]);
}
else
{
listMembersConsolidated.Add(item[0]);
}
}
But this does not give me the desired result -> always the same person in the result
Does anybody have a hint for me?
Would be highly appreciated.
Thank you in advance.

I just created very simple console application in c# based on entity framework.
I created Product Entity and added around 15 products.
Then I added all these entity products in an Entity collection.
So that now I have almost same req as you need.
What I did is that keep only those Records in my entitycollection which have UnitsInStock highest among a Product ID.
For ex: For Product ID 1 I have only taken record with UnitsInStock =40
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityCollectionTesting
{
class Program
{
static void Main(string[] args)
{
var productList =
new List<Product> {
new Product { ProductID = 1, ProductName = "Chai", Category = "Beverages", UnitPrice = 18.0000M, UnitsInStock = 39 },
new Product { ProductID = 2, ProductName = "Chang", Category = "Beverages", UnitPrice = 19.0000M, UnitsInStock = 17 },
new Product { ProductID = 3, ProductName = "Aniseed Syrup", Category = "Condiments", UnitPrice = 10.0000M, UnitsInStock = 13 },
new Product { ProductID = 4, ProductName = "Chef Anton's Cajun Seasoning", Category = "Condiments", UnitPrice = 22.0000M, UnitsInStock = 53 },
new Product { ProductID = 5, ProductName = "Chef Anton's Gumbo Mix", Category = "Condiments", UnitPrice = 21.3500M, UnitsInStock = 0 },
new Product { ProductID = 6, ProductName = "Grandma's Boysenberry Spread", Category = "Condiments", UnitPrice = 25.0000M, UnitsInStock = 120 },
new Product { ProductID = 7, ProductName = "Uncle Bob's Organic Dried Pears", Category = "Produce", UnitPrice = 30.0000M, UnitsInStock = 15 },
new Product { ProductID = 8, ProductName = "Northwoods Cranberry Sauce", Category = "Condiments", UnitPrice = 40.0000M, UnitsInStock = 6 },
new Product { ProductID = 9, ProductName = "Mishi Kobe Niku", Category = "Meat/Poultry", UnitPrice = 97.0000M, UnitsInStock = 29 },
new Product { ProductID = 10, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 31 },
new Product { ProductID = 1, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 40 },
new Product { ProductID = 2, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 56 },
new Product { ProductID = 3, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 11 },
new Product { ProductID = 4, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 12 },
new Product { ProductID = 5, ProductName = "Ikura", Category = "Seafood", UnitPrice = 31.0000M, UnitsInStock = 1 }
};
EntityCollection<Product> entityCollection = new EntityCollection<Product>();
EntityCollection<Product> newCollection = new EntityCollection<Product>();
foreach (var VARIABLE in productList)
{
entityCollection.Add(VARIABLE);
newCollection.Add(VARIABLE);
}
foreach (var ec in entityCollection)
{
foreach (var nc in newCollection)
{
if (ec.ProductID == nc.ProductID)
{
if (ec.UnitsInStock > nc.UnitsInStock)
{
newCollection.Remove(nc);
break;
}
}
}
}
foreach (var VARIABLE in newCollection)
{
Console.WriteLine($"{VARIABLE.ProductID} and {VARIABLE.UnitsInStock}");
}
Console.ReadLine();
}
}
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public decimal UnitPrice { get; set; }
public int UnitsInStock { get; set; }
}
}

You can try this. I've used sample list but you can apply with your entity collection. Enjoy coding
List<Employee> employees = new List<Employee>();
var newEmployeList = employees.Distinct().ToList();

Related

ASP.NET-MVC4 - Linq query to select largest "supplier" in a database

i have 2 tables in a database
supplier table: SupplierID - SupplierName
product table: ProductID - ProductName - UnitsInStock - SupplierID
how can i select the supplier that has largest UnitsInStock?
here's the code i have
private storeDBEntities2 db1 = new storeDBEntities2();
public ActionResult Index()
{
var product = db1.Products.Where(e => e.UnitsInStock == 0);
var largestSupplier = db1.Products.GroupBy(e => e.SupplierID);
Product minimord = db1.Products.OrderBy(e => e.UnitsOnOrder).FirstOrDefault();
var supplier = // this is the query i am struggling with
AllModelsProduct all = new AllModelsProduct { Iproduct = product.ToList(), product = new Product(),largestSupplierOfTheStore = supplier,minimumOrders = minimord };
return View(all);
}
here's a picture of my data
i need to get supplierID 345 as we have 20 units belong to him in store which is greater than the other supplier with 5 + 3 + 0 = 8 units
If all you're looking to do is find the supplier with the largest number of UnitsInStock then this should do the trick.
I have created a dotNetFiddle for you to observe.
But here it is anyway:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Supply> lstSuppliers = new List<Supply>();
Supply supply1 = new Supply() { ID = 1, SupplierName = "Supplier One"};
Supply supply2 = new Supply() { ID = 2, SupplierName = "Supplier Two"};
lstSuppliers.Add(supply1);
lstSuppliers.Add(supply2);
Product product1 = new Product() {ID = 1, UnitsInStock = 3, SupplierID = 1};
Product product2 = new Product() {ID = 2, UnitsInStock = 3, SupplierID = 2};
Product product3 = new Product() {ID = 3, UnitsInStock = 5, SupplierID = 1};
List<Product> lstAllProducts = new List<Product>();
lstAllProducts.Add(product1);
lstAllProducts.Add(product2);
lstAllProducts.Add(product3);
var findSupplierId = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).OrderByDescending(x => x.Count).First().Supplier;
Console.WriteLine(findSupplierId);
Console.WriteLine(lstSuppliers.Single(x => x.ID.ToString() == findSupplierId).SupplierName);
}
}
public class Supply{
public int ID {get;set;}
public string SupplierName {get;set;}
}
public class Product{
public int ID {get;set;}
public int UnitsInStock {get;set;}
public int SupplierID {get;set;}
}
This uses the GroupBy, along with creating anonymous classes to get the desired outcome.
Let me know if this helps!
Update - To show if multiple suppliers have the same units in stock
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Supply> lstSuppliers = new List<Supply>();
Supply supply1 = new Supply() { ID = 1, SupplierName = "Supplier One"};
Supply supply2 = new Supply() { ID = 2, SupplierName = "Supplier Two"};
Supply supply3 = new Supply() { ID = 3, SupplierName = "Supplier Three"};
lstSuppliers.Add(supply1);
lstSuppliers.Add(supply2);
lstSuppliers.Add(supply3);
Product product1 = new Product() {ID = 1, UnitsInStock = 3, SupplierID = 1};
Product product2 = new Product() {ID = 2, UnitsInStock = 3, SupplierID = 2};
Product product3 = new Product() {ID = 3, UnitsInStock = 5, SupplierID = 1};
Product product4 = new Product() {ID = 4, UnitsInStock = 8, SupplierID = 3};
List<Product> lstAllProducts = new List<Product>();
lstAllProducts.Add(product1);
lstAllProducts.Add(product2);
lstAllProducts.Add(product3);
lstAllProducts.Add(product4);
// finds largest supplier
//var findSupplierId = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).OrderByDescending(x => x.Count).First().Supplier;
//Console.WriteLine(lstSuppliers.Single(x => x.ID.ToString() == findSupplierId).SupplierName);
// What if there are multiple suppliers with the same number of units in stock?
// first - we have to find the largest number of units in stock
var findLargestNumberUIS = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).Max(x => x.Count); // 8
// second - gather a list of suppliers where their units in stock == findLargestNumberUIS
var lstOfLargestSuppliers = lstAllProducts.GroupBy(x => x.SupplierID).Select(x => new{ Supplier = x.Key.ToString(), Count = x.Sum(g => g.UnitsInStock)}).Where(x => x.Count == findLargestNumberUIS).ToList();
// third - loop through lstOfLargestSuppliers to get all suppliers that have the same amount of units in stock which happen to be the largest
foreach(var item in lstOfLargestSuppliers){
var supplier = lstSuppliers.Single(x => x.ID.ToString() == item.Supplier).SupplierName;
Console.WriteLine(supplier); // print the supplier names to console
// Output - Supplier One
// Supplier Three
}
}
}
public class Supply{
public int ID {get;set;}
public string SupplierName {get;set;}
}
public class Product{
public int ID {get;set;}
public int UnitsInStock {get;set;}
public int SupplierID {get;set;}
}

Cannot group data in LINQ

I have a question about a LINQ grouping.
I thought that grouping would be a simple matter of using the GroupBy function on the result set and specifying what to group it by. However my items appear to not be grouping together and instead are displaying as if the GroupBy function wasn't there. I want to group by the itemPk, but I'm can't seem to do it. I have tried grouping by both category.ItemFk and Item.Itempk, but no luck. Could someone give me a pointer on this?
var itemIds = items.Select(i => i.ItemId).ToList();
var itemAndCatJoin =
from item in Context.SCS_Items
join category in Context.SCS_ItemCategories
on item.ItemPk equals category.ItemFk
into temp
from category in temp.DefaultIfEmpty()
select new ExportItemTable
{
Category = category,
Item = item
};
return itemAndCatJoin.Where(i => itemIds.Contains(i.Item.ItemPk))
.GroupBy(n => new {n.Item, n.Category})
.Select(i => new ExportableItem
{
ItemPk = i.Key.Item.ItemPk,
Name = i.Key.Item.Name,
Description = i.Key.Item.Description,
Price = i.Key.Item.Price,
Category = i.Key.Category.Category.Category_Name,
GLDepartment = i.Key.Category.GL_Department.Name ?? "",
GLName = i.Key.Category.GL_Name.Name ?? "",
StartDate = i.Key.Item.StartDate,
EndDate = i.Key.Item.EndDate,
FiscalYear = i.Key.Item.SCS_FiscalYear.Name,
School = i.Key.Item.School != null ? i.Key.Item.School.School_Name : i.Key.Item.Board.Board_Name,
Beneficiary = i.Key.Item.SCS_Beneficiary.Name,
Quantity = i.Key.Item.MaxQuantity,
Deleted = i.Key.Item.DeletedFlag,
OptionalStudents = i.Key.Item.SCS_Attachments.Where(a => !a.IsRequired).SelectMany(a => a.SCS_StudentAttachments).Where(s => !s.DeletedFlag).Select(s => s.StudentFk).Distinct().Count(),
RequiredStudents = i.Key.Item.SCS_Attachments.Where(a => a.IsRequired).SelectMany(a => a.SCS_StudentAttachments).Where(s => !s.DeletedFlag).Select(s => s.StudentFk).Distinct().Count(),
IsPublic = i.Key.Item.IsPublic,
AllowRecurring = i.Key.Item.AllowRecurringPayments,
EffectiveCutoff = i.Key.Item.SCS_Attachments.Where(a => !a.DeletedFlag && a.CourseDropCutoff.HasValue).Select(a => a.CourseDropCutoff).OrderBy(a => a).FirstOrDefault(),
CreatedDate = i.Key.Item.CreatedDate
}).OrderBy(i => i.ItemPk).ToList();
}
your groupbyy is indeed doing nothing for you, you need to tell the groupby what to group by....
like
.GroupBy(n => n.Category)
Here is a simple example to your grouping question:
class Program
{
static void Main()
{
var allItems = GetAllItems();
var groups = from item in allItems
group item by item.Category
into newGroup
select newGroup;
foreach (var group in groups)
{
Console.WriteLine($"\nCategory: {group.Key}");
foreach (var item in group)
{
Console.WriteLine($"{item.Name}: {item.Price}");
}
}
Console.ReadLine();
}
static List<Category> GetAllCategories()
{
return new List<Category>()
{
new Category() { Id = 1, Name = "Programming Books" },
new Category() { Id = 2, Name = "Fiction Books" }
};
}
static List<Item> GetAllItems()
{
return new List<Item>()
{
new Item() { Id = 1, Name = "Embedded Linux", Category = 1, Price = 9.9 },
new Item() { Id = 2, Name = "LINQ In Action", Category = 1, Price = 36.19 },
new Item() { Id = 3, Name = "C# 6.0 and the .NET 4.6 Framework", Category = 1, Price = 40.99 },
new Item() { Id = 4, Name = "Thinking in LINQ", Category = 1, Price = 36.99 },
new Item() { Id = 5, Name = "The Book Thief", Category = 2, Price = 7.99 },
new Item() { Id = 6, Name = "All the Light We Cannot See", Category = 2, Price = 16.99 },
new Item() { Id = 7, Name = "The Life We Bury", Category = 2, Price = 8.96 }
};
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int Category { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
This example is simple enough for anyone new to LINQ. I am sure you can make some adjustment to make it work for your specific issue. Hope this will help.

Using #Html.DropDownListFor

I created list of objects in controller and I would like show one of property in DropDownList. This is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
List<Product> product = new List<Product>();
product.Add(new Product() { ProductId = 1, Name = "apple", Price = 1.09 });
product.Add(new Product() { ProductId = 2, Name = "peach", Price = 1.57 });
product.Add(new Product() { ProductId = 3, Name = "banana", Price = 1.15 });
product.Add(new Product() { ProductId = 4, Name = "watermelon", Price = 4.50 });
product.Add(new Product() { ProductId = 5, Name = "melon", Price = 5.06 });
product.Add(new Product() { ProductId = 6, Name = "strawberries", Price = 6.99 });
product.Add(new Product() { ProductId = 7, Name = "raspberries", Price = 2.20 });
return View(product);
}
}
And I try use it into my View below but it return false. How can I use helper #Html.DropDownListFor?
#foreach(var name in Model.Name)
{
#Html.DropDownListFor(name.Name ,name.ToString())
}
I am assuming that for the Product class looks like:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
And let us say that you have the following model:
public class ProductModel
{
public int MyProductId { get; set; }
}
And finally you have created the list of Products (like you have shown)
List<Product> product = new List<Product>();
produkt.Add(new Product() { ProductId = 1, Name = "apple", Price = 1.09 });
produkt.Add(new Product() { ProductId = 2, Name = "peach", Price = 1.57 });
produkt.Add(new Product() { ProductId = 3, Name = "banana", Price = 1.15 });
produkt.Add(new Product() { ProductId = 4, Name = "watermelon", Price = 4.50 });
produkt.Add(new Product() { ProductId = 5, Name = "melon", Price = 5.06 });
produkt.Add(new Product() { ProductId = 6, Name = "strawberries", Price = 6.99 });
produkt.Add(new Product() { ProductId = 7, Name = "raspberries", Price = 2.20 });
In your view you can create a drop down list like so:
#model ProductModel
#Html.DropDownListFor(n => n.MyProductId,
new SelectList(product, "ProductId", "Name"))
For more info you can have a look at this article
Give this a go :)
#model App.Models.Model
#Html.DropDownListFor(x => x.ProductId, new SelectList(Product, "Name", "Price"))

Doing multiple joins within a LINQ statement

Can someone help me translate the following SQL query into a LINQ format.
SELECT a.ID,
a.HostID,
h.URL,
a.SourceURL,
a.TargetURL,
c.Value,
a.ExtFlag
FROM Link a
INNER JOIN Host h
ON h.ID = a.HostID
INNER JOIN Ref c
ON a.ResponseCode = c.SubType
AND c.Type = 'HTTP Status'
Many Thanks
I think it would be something like:
var result = from a in Context.DGApprovedLink
join h in Context.DGHost on a.HostID equals h.ID
join c in Context.DGConfig on a.ResponseCode equals c.SubType
where c.Type == "HTTP Status"
select new {
a.ID,
a.HostID,
h.URL,
a.SourceURL,
a.TargetURL,
c.Value,
a.ExtFlag };
Create Unit test class using MStest and copy the code
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinqTest.Test
{
public class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
public DateTime? DOB { get; set; }
public decimal Salary { get; set; }
public DateTime DOJ { get; set; }
public bool IsActive { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public double Price { get; set; }
}
public class BookOrder
{
public int OrderId { get; set; }
public int EmpId { get; set; }
public int BookId { get; set; }
public int Quantity { get; set; }
}
[TestClass]
public class Linqtest
{
List<Employee> Employees;
List<Book> Books;
List<BookOrder> Orders;
[TestInitialize]
public void InitializeData()
{
Employees = new List<Employee>();
Books = new List<Book>();
Orders = new List<BookOrder>();
Employees.Add(new Employee(){EmpId = 1, Name ="Test1" , DOB = new DateTime(1980,12,15),IsActive = true,Salary = 4500});
Employees.Add(new Employee() { EmpId = 11, Name = "Test2", DOB = new DateTime(1981, 12, 15), IsActive = true, Salary = 3500 });
Employees.Add(new Employee() { EmpId = 5, Name = "Test3", DOB = new DateTime(1970, 2, 15), IsActive = true, Salary = 5500 });
Employees.Add(new Employee() { EmpId = 8, Name = "Test4", DOB = new DateTime(1978, 1, 15), IsActive = true, Salary = 7500 });
Employees.Add(new Employee() { EmpId = 9, Name = "Test5", DOB = new DateTime(1972, 2, 5), IsActive = true, Salary = 2500 });
Employees.Add(new Employee() { EmpId = 10, Name = "Test6", DOB = new DateTime(1980, 10, 8), IsActive = false, Salary = 5500 });
Employees.Add(new Employee() { EmpId = 15, Name = "Test7", DOB = new DateTime(1983, 11, 25), IsActive = true, Salary = 3500 });
Books.Add(new Book(){BookId = 2, Price = 24.99,Title = "British Food"});
Books.Add(new Book() { BookId = 5, Price = 4.99, Title = "Holidays in UK" });
Books.Add(new Book() { BookId = 7, Price = 7.99, Title = "UK Laws" });
Orders.Add(new BookOrder(){EmpId = 1,OrderId = 1,BookId = 2,Quantity = 3});
Orders.Add(new BookOrder() { EmpId = 1, OrderId = 1, BookId = 5, Quantity = 1 });
Orders.Add(new BookOrder() { EmpId = 1, OrderId = 2, BookId = 7, Quantity = 5 });
Orders.Add(new BookOrder() { EmpId = 11, OrderId = 3, BookId = 2, Quantity = 3 });
Orders.Add(new BookOrder() { EmpId = 11, OrderId = 4, BookId = 7, Quantity = 3 });
}
[TestMethod]
public void CheckEmpCount()
{
var res = Employees
.Where(e => e.EmpId > 5)
.Where(t =>t.Salary>=5000);
Assert.AreEqual(2,res.Count());
res = Employees
.Where(e => e.EmpId > 5);
Assert.AreEqual(5,res.Count());
}
[TestMethod]
public void TestGroupBy()
{
var res = from e in Employees
group e by e.Salary;
Assert.AreEqual(5,res.Count());
var res1 = Employees.GroupBy(e => e.Salary);
Assert.AreEqual(5, res1.Count());
}
[TestMethod]
public void TestJoin()
{
var res = from o in Orders
join Employee e in Employees
on o.EmpId equals e.EmpId
where o.EmpId == 11
select o;
Assert.AreEqual(2,res.Count());
}
[TestMethod]
public void TestJoinData()
{
var res = from o in Orders
join Employee e in Employees
on o.EmpId equals e.EmpId
join Book b in Books
on o.BookId equals b.BookId
orderby e.EmpId
select new {o.OrderId, e.Name, b.Title, b.Price};
Assert.AreEqual("Test1", res.First().Name);
}
}
}

LINQ - GroupBy a key and then put each grouped item into separate 'buckets'

I have a list of items as such:
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public int ListId { get; set; }
}
1 Test1 1
2 Test2 1
3 Test3 1
4 List 2
5 List2 2
6 Testing 3
7 Testing2 3
8 Testing3 3
Is there a way for me to group by the ListId and put them into each separate buckets, i.e, ListId1 bucket will have all items with ListId == 1. The list is dynamically returned from SQL, so I don't know before hand how many ListId there will be.
You can use GroupBy:
var groups = items.GroupBy(item => item.ListId);
foreach(var group in groups)
{
Console.WriteLine("List with ID == {0}", group.Key);
foreach(var item in group)
Console.WriteLine(" Item: {0}", item.ItemName);
}
Let's create your list of items:
List<Item> items = new List<Item>();
items.Add(new Item() { ItemId = 1, ItemName = "Test1", ListId = 1 });
items.Add(new Item() { ItemId = 2, ItemName = "Test2", ListId = 1 });
items.Add(new Item() { ItemId = 3, ItemName = "Test3", ListId = 1 });
items.Add(new Item() { ItemId = 4, ItemName = "List", ListId = 2 });
items.Add(new Item() { ItemId = 5, ItemName = "List2", ListId = 2 });
items.Add(new Item() { ItemId = 6, ItemName = "Testing", ListId = 3 });
items.Add(new Item() { ItemId = 7, ItemName = "Testing2", ListId = 3 });
items.Add(new Item() { ItemId = 8, ItemName = "Testing3", ListId = 3 });
var groupByResult = items.GroupBy(i => i.ListId);
After this GroupBy call, groupByResult is a variable of type IEnumerable<IGrouping<int, Item>> which is basically a collection of objects that implement IGrouping interface. This allows you to iterate through all items as IGrouping is derived from IEnumerable<> and has an extra field named Key:
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
{
TKey Key { get; }
}
Briefly said, a GroupBy method call returns a list of lists. An outer list corresponds to 'buckets' as you mentioned in your question. Then each 'bucket' contains items corresponding to that 'bucket'. To be specific to your example, the value of groupByResult is depicted in this screenshot. As we can see there, your initial collection was grouped into three different buckets that have 3, 2 and 3 items, respectively.
As for accessing items in these groups, you can use simple LINQ:
List<Item> firstBucketItems = groupByResult.First(i => i.Key == 1).ToList();
List<Item> secondBucketItems = groupByResult.First(i => i.Key == 2).ToList();
List<Item> thirdBucketItems = groupByResult.First(i => i.Key == 3).ToList();
Or you can just iterate through all items:
foreach (var itemGroup in groupByResult)
{
int groupKey = itemGroup.Key;
foreach (Item item in itemGroup)
{
// Do whatever...
}
}
IList<Student> studentList = new List<Student>()
{
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 }
};
var groupedResult = from s in studentList group s by s.Age;
//iterate each group
foreach (var ageGroup in groupedResult)
{
Console.WriteLine("Age Group: {0}", ageGroup.Key); //Each group has a key
foreach(Student s in ageGroup) // Each group has inner collection
Console.WriteLine("Student Name: {0}", s.StudentName);
}
Basic format
var res = (from i in items
group i by i.ListId into g
select );
You can also do this by following
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>();
items.Add(new Item() { ItemId = 1, ItemName = "Test1", ListId = 1 });
items.Add(new Item() { ItemId = 2, ItemName = "Test2", ListId = 1 });
items.Add(new Item() { ItemId = 3, ItemName = "Test3", ListId = 1 });
items.Add(new Item() { ItemId = 4, ItemName = "List", ListId = 2 });
items.Add(new Item() { ItemId = 5, ItemName = "List2", ListId = 2 });
items.Add(new Item() { ItemId = 6, ItemName = "Testing", ListId = 3 });
items.Add(new Item() { ItemId = 7, ItemName = "Testing2", ListId = 3 });
items.Add(new Item() { ItemId = 8, ItemName = "Testing3", ListId = 3 });
var groupByResult = items.GroupBy(i => i.ListId);
List<GroupedItems> betterGroups = new List<GroupedItems>();
foreach (var groupedItem in groupByResult)
{
betterGroups.Add(new GroupedItems() { ListId = groupedItem.Key, Items = groupedItem.ToList() });
// ListId = 1 , List<Item> 3 records
// ListId = 2 , List<Item> 2 records
// ListId = 3 , List<Item> 3 records
// You can iteratre throught ListId
}
}
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public int ListId { get; set; }
}
public class GroupedItems
{
public int ListId {get; set;}
public List<Item> Items {get; set;}
}
}
donetFiddle example Link

Categories