Ken H

Ken H

  • NA
  • 646
  • 361.7k

LINQ type conversion in c#

Feb 5 2015 10:37 AM
Hello friend,
 
 My questions are as follows:
 
 
 
namespace LINQSample
{
public class Product {

public Product() { }

public Product(int ci, string city, string pn)
{
this.CategoryID = ci;
this.City = city;
this.ProductName = pn;
}

public int CategoryID { get; set; }
public string City { get; set; }
public string ProductName { get; set; }
public int Qty { get; set; }
}

class Program
{
static void InitializeProduct(Product product)
{
char[] pn = new char[26];
int[] category = new int[5] { 1, 2, 3, 4, 5};
string[] city = new string[3] { "Edinburgh", "Hong Kong", "San Francisco" };

for (int i = 0; i < 26; i++){

pn[i] = new char();
pn[i] = (char)(97 + i);
}

Random rand = new Random();

for (int i = 0; i < 5; i++) product.ProductName += pn[rand.Next(0, 26)];

product.City = city[rand.Next(0, 3)];
product.CategoryID = category[rand.Next(0, 5)];
product.Qty = rand.Next(1, 100);

}
static void Main(string[] args)
{
Product[] products = new Product[20];

for (int i = 0; i < 20; i++) {

products[i] = new Product();
System.Threading.Thread.Sleep(20);
InitializeProduct(products[i]);
}

Console.WriteLine();

//var _products = from product in products
// group product by product.City into temp
// orderby temp.Key ascending
// select new
// {
// City = temp.Key,
// Total=temp.Sum(product=>product.Qty),
// };
// Type conversion error occurred in here.
IEnumerable<Product> _products = from product in products
group product by product.City into temp
orderby temp.Key ascending
select new
{
City = temp.Key,
Total = temp.Sum(product => product.Qty),
};

foreach (var item in _products){
Console.WriteLine("City:" + item.City + " Product Name:" + " Quantity:" + item.Total);

Console.WriteLine();
}

}
}
 
 
Thanks in advance.

Answers (2)