How to Get the Index Position of the Results
Select and SelectMany
expose an overload that surfaces the index position (starting at zero)
for each returned element in the Select projection. It is surfaced as an
overloaded parameter argument of the selector lambda expression and is only accessible using the extension method query syntax. Listing 1 demonstrates how to access and use the index position value in a Select projection. As shown in Output 1, this example simply adds a ranking number for each select result string.
Listing 1. A zero-based index number is exposed by the Select and SelectMany operators—see Output 1
List<CallLog> callLog = CallLog.SampleData();
var q = callLog.GroupBy(g => g.Number)
.OrderByDescending(g => g.Count())
.Select((g, index) => new
{
number = g.Key,
rank = index + 1,
count = g.Count()
});
foreach (var c in q)
Console.WriteLine(
"Rank {0} - {1}, called {2} times.",
c.rank, c.number, c.count);
|
Output 1.
Rank 1 - 885 983 8858, called 6 times.
Rank 2 - 546 607 5462, called 6 times.
Rank 3 - 364 202 3644, called 4 times.
Rank 4 - 603 303 6030, called 4 times.
Rank 5 - 848 553 8487, called 4 times.
Rank 6 - 165 737 1656, called 2 times.
Rank 7 - 278 918 2789, called 2 times.
How to Remove Duplicate Results
The Distinct
standard query operator performs the role of returning only unique
instances in a sequence. The operator internally keeps track of the
elements it has returned and skips the second and subsequent duplicate elements as it returns resulting elements.
The Distinct operator
is not supported in the query expression syntax, so it is often appended
to the end of a query using extension method syntax. To demonstrate how
it is used, the following code removes duplicate strings. The Console
output from this code is
Peter
Paul
Mary
Janet
string[] names = new string[] { "Peter", "Paul",
"Mary", "Peter", "Paul", "Mary", "Janet" };
var q = (from s in names
where s.Length > 3
select s).Distinct();
foreach (var name in q)
Console.WriteLine(name);