Note that there are some explanatory texts on larger screens.

plurals
  1. POc# - why this OrderBy parameter is wrong?
    primarykey
    data
    text
    <p>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:</p> <pre><code>namespace StudyDemo { public class MyDelegate { public delegate TResult DelegateOrder&lt;in T, out TResult&gt;(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&lt;Product&gt; GetSampleProducts() { return new List&lt;Product&gt; { 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&lt;Product&gt; products = Product.GetSampleProducts(); Func&lt;Product, string&gt; orderDelegate2 = myOrder; foreach (Product product in products.OrderBy(orderDelegate2)) { /* Do something */ } MyDelegate.DelegateOrder&lt;Product, string&gt; myOrder2 = myOrder; foreach (Product product in products.OrderBy(myOrder2)) /* not functioning, why? */ { /* Do something */ } } } } </code></pre> <p>Note Below: <strong>DelegateOrder</strong> delegate and Func delegate are the same. I just copy the <strong>Func</strong> delegate to <strong>DelegateOrder</strong> delegate.</p> <p>In the above code example, the line <code>foreach (Product product in products.OrderBy(myOrder2))</code> does not functioning, could anyone kindly tell me why?</p> <p>This is the error when you compile the code:</p> <p><code>The type arguments for method 'System.Linq.Enumerable.OrderBy&lt;TSource,TKey&gt;(System.Collections.Generic.IEnumerable&lt;TSource&gt;, System.Func&lt;TSource,TKey&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly.</code></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload