I'm currently learning C# and trying to get the hang of LINQ. I am trying to create two classes : Store and Produces and I want to return the object in them based on the correspond ID. I planned to do this using LINQ but I run into this error.
System.InvalidOperationException: 'Failed to compare two elements in the array.' ArgumentException: At least one object must implement IComparable.
I of course tried to implement IComparable into the classes by adding something like this:
public class Store : IComparable<Store>
{
public int CompareTo([AllowNull] Store other)
{
throw new NotImplementedException();
}
}
Unfortunately this did not fix the error. I have tried editing the CompareTo method a but but to no success, what should I do?
Here is my full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
namespace LINQ_Testing
{
class Program
{
static void Main(string[] args)
{
List<Store> MarketPlace = new List<Store>();
//Stores
MarketPlace.Add(new Store { Name = "SuperMarket", ID = 1 });
MarketPlace.Add(new Store { Name = "Electronics", ID = 2 });
MarketPlace.Add(new Store { Name = "Clothing", ID = 3 });
MarketPlace.Add(new Store { Name = "Appliance", ID = 4 });
List<Produces> Products = new List<Produces>();
//Products
Products.Add(new Produces { Names = new string[] { "Vegetables", "Dairy", "Fruits" }, Prices = new double[] { 3.00, 2.00, 1.50 }, StoreID = 1 });
Products.Add(new Produces { Names = new string[] { "Portable Electronics", "Stationary Electronics", "Medical Electronics" }, Prices = new double[] { 200.00, 750.00, 550.00 }, StoreID = 2 });
Products.Add(new Produces { Names = new string[] { "Coats", "Dresses", "Leggings" }, Prices = new double[] { 35.00, 45.00, 25.00 }, StoreID = 3 });
Products.Add(new Produces { Names = new string[] { "Home Appliances", "Kitchen Appliances", "Industrial Appliances" }, Prices = new double[] { 500.00, 350.00, 850.00 }, StoreID = 1 });
var innerJoin = from market in MarketPlace
orderby market.ID
join product in Products
on market.ID
equals product.StoreID
into marketGroup
select new
{
market = market.Name,
product = from market2 in marketGroup
orderby market2.Names
select market2
};
foreach (var item in innerJoin)
{
Console.WriteLine(item.market);
foreach(var item2 in item.product)
{
item2.ToString();
}
}
}
}
}
public class Store
{
public string Name { get; set; }
public int ID { get; set; }
}
public class Produces
{
public string[] Names = new string[3];
public int StoreID { get; set; }
public double[] Prices = new double[3];
public override string ToString()
{
return "Contains Products such as: " /*NamesArray()*/ + " with prices such as : " /*+ PricesArray()*/;
}
private string NamesArray()
{
int i;
for (i = 0; i <= 3 - 1; i++)
{
return Names[i]+",";
}
return "";
}
private string PricesArray()
{
int i;
for(i = 0; i <= 3 - 1; i++)
{
var pr = Prices[i].ToString();
return pr;
}
return "";
}
}