I’m running problem with the Delegate and OrderBy extension method.
Could anyone please tell me why? Thanks in advance.
Below is the whole code:
namespace StudyDemo
{
public class MyDelegate
{
public delegate TResult DelegateOrder<in T, out TResult>(T arg);
}
public class Product
{
public string Name { get; private set; }
public decimal? Price { get; set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
/* private parameterless constructor for the sake of the new property-based initialization. */
Product() { }
public static List<Product> GetSampleProducts()
{
return new List<Product>
{
new Product { Name="West Side Story", Price=9.99m },
new Product { Name="Assassins", Price=14.99m },
new Product { Name="Frogs", Price=13.99m },
new Product { Name="Sweeney Todd", Price=10.99m }
};
}
public override string ToString()
{
return string.Format("{0}: {1}", Name, Price);
}
}
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
public string myOrder(Product p)
{
return p.Name;
}
private void button2_Click(object sender, EventArgs e)
{
List<Product> products = Product.GetSampleProducts();
Func<Product, string> orderDelegate2 = myOrder;
foreach (Product product in products.OrderBy(orderDelegate2))
{
/* Do something */
}
MyDelegate.DelegateOrder<Product, string> myOrder2 = myOrder;
foreach (Product product in products.OrderBy(myOrder2)) /* not functioning, why? */
{
/* Do something */
}
}
}
}
Note Below:
DelegateOrder delegate and Func delegate are the same.
I just copy the Func delegate to DelegateOrder delegate.
In the above code example, the line foreach (Product product in products.OrderBy(myOrder2))
does not functioning, could anyone kindly tell me why?
This is the error when you compile the code:
The type arguments for method 'System.Linq.Enumerable.OrderBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
The compiler has no way of converting your custom delegate type DelegateOrder to System.Func (which is the argument expected for IEnumerable.OrderBy).
This is despite the fact that both essentially have the same signature. Using System.Func is preferred because it provides for interop between delegates with the same signature.
If I were you I would simply use an inline anonymous function to handle the ordering:
Interestingly – for bonus points – if you did want to use the delegate object the following would work: