using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
List<Product> productList = new List<Product>
{
new Product { ProductId = 1, Name = "Product1", Price = 100, CategoryId = 1 },
new Product { ProductId = 2, Name = "Product2", Price = 200, CategoryId = 1 },
new Product { ProductId = 3, Name = "Product3", Price = 300, CategoryId = 2 },
new Product { ProductId = 4, Name = "Product4", Price = 400, CategoryId = 2 },
new Product { ProductId = 5, Name = "Product5", Price = 500, CategoryId = 3 },
new Product { ProductId = 6, Name = "Product6", Price = 600, CategoryId = 3 }
};
List<Category> categoryList = new List<Category>
{
new Category { CategoryId = 1, Name = "Category1" },
new Category { CategoryId = 2, Name = "Category2" },
new Category { CategoryId = 3, Name = "Category3" }
};
// Group products by category and select relevant data
var groupedProducts = categoryList
.Select(c => new
{
Category = new Category
{
CategoryId = c.CategoryId,
Name = c.Name
},
Products = productList
.Where(p => p.CategoryId == c.CategoryId && p.Price > 100)
.OrderBy(p => p.Name)
.Select(p => new Product
{
ProductId = p.ProductId,
Name = p.Name,
Price = p.Price,
CategoryId = p.CategoryId,
})
.ToList()
})
.ToList();
// Display the results
foreach (var g in groupedProducts)
{
Console.WriteLine($"Category: {g.Category.Name}");
foreach (var p in g.Products)
{
Console.WriteLine($"\tProduct ID: {p.ProductId}, Name: {p.Name}, Price: {p.Price}");
}
}
}
}
var catlist = categoryList
.Select(c => new
{
Category = new Category
{
CategoryId = c.CategoryId,
Name = c.Name
},
Products = productList
.Where(p => p.CategoryId == c.CategoryId)
.Distinct() // Ensure distinct products
.OrderByDescending(p => p.Price) // Order products by price in descending order
.Skip(1) // Skip the first product
.Take(2) // Take only 2 products
.Select(p => new Product
{
ProductId = p.ProductId,
Name = p.Name.ToLower(), // Convert product name to lowercase
Price = p.Price * 0.9m // Apply a discount of 10% to the product price
}).ToList()
})
.Where(cat => cat.Products.Any()) // Filter out categories with no products
.ToList();