views:

637

answers:

2

Can someone please help be take apart the elements here and help me understand what they are?

public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
)

What is TSource and TKey? What is a keySelector? What the heck is an IOrderedEnumerable?

What does Func<> do??

Why is MSDN so cryptic?

+4  A: 

Break Down

  • TSource: This is the type of elements in the collection which need to be ordered
  • TKey: The type key by which the elements are ordered.
  • Func<TSource,TKey>: Delegate which will return a key for a given element in the collection

This function is essentially a sorting function. As such it needs a way to compare the elements in the collection. This particular method assumes that for a given object there is a corresponding key value by which they can be sorted.

Take for example the following class Student

class Student { 
  string Name { get; set; }
  ...
}

If I wanted to sort a collection of Student instances by their name I could do the following

IEnumerable<Student> col = GetTheStudents();
var ordered = col.OrderByDescending( x => x.Name );

In this case the values would be as follows

  • TSource: Student
  • TKey: String
  • Func<TSource,TKey>: This is the passed in lambda expression x => x.Name
JaredPar
Great response, one more thing: I am having trouble understanding where you get x, or is x being declared right there? Why the 'equal to our greater than'?
shogun
Likewise what if you just put '=' or if you put '=<' (equal to or less than) ?
shogun
@Ryan, x is declared as a part of the lambda expression. A more expanded form is the following: delegate (string x) { return x.Name;}
JaredPar
A: 

I just wonder, what is exactly unclear on MSDN? Here is the topic: http://msdn.microsoft.com/en-us/library/bb548916.aspx

And here are some answers to your questions from that topic:

Type Parameters

TSource - The type of the elements of source.

TKey - The type of the key returned by keySelector.

Parameters

source - A sequence of values to order.

keySelector - A function to extract a key from an element.

comparer - An IComparer to compare keys.

Return Value

An IOrderedEnumerable whose elements are sorted in descending order according to a key.

Also, there are remarks and an example. What you posted here is just a signature of the method.

Alexandra Rusina
ok you're right, I was just being frustrated, I guess it's not MSDN that's cryptic to me it's the LINQ :)
shogun
I'd say it's not just LINQ. C# has changed a lot from 1.0 to 3.0. Probably, it will be good for you to just get a good book about C# 3.0 and read about generics, extension methods, lambda expressions, delegates, and yes, LINQ. Right now it seams that you simply cannot read new C# syntax.
Alexandra Rusina