LINQ
-
Upload
chuck-durfee -
Category
Technology
-
view
65 -
download
0
Transcript of LINQ
Chuck Durfee, 3 October 2012
BIGDATA
Enumerable.Select(
Enumerable.OrderBy(
Enumerable.Where(names, s => s.Length == 5),
s => s
),
s => s.ToUpper()
);
versus
names.Where(s => s.Length == 5)
.OrderBy(s => s)
.Select(s => s.ToUpper())
, my dear Watson
1.0delegate bool FilterMethod(string s);
private bool IsFiveLetterName(string s) {
return s.Length == 5;
}
public DotNet10Land()
{
FilterMethod filter = IsFiveLetterName;
}
delegate bool FilterMethod(string s);
public DotNet20Land(){FilterMethod filter =
delegate(string s) {return s.Length == 5;
};}
2.0
C# 3 = .NET 3.5delegate bool FilterMethod(string s);
public DotNet35Land()
{
string chuck = "chuck";
FilterMethod filter =
delegate(string s) {
return s != chuck && s.Length == 5;
};
}
Func// delegate bool FilterMethod(string s);
public DotNet35Land()
{
Func<string, bool> filter =
delegate(string s) {
return s.Length == 5;
};
}
Func<string, bool>
Func<string, int, DateTime>
Func<List<string>, int, bool>
but not
Func<string, System.Void>
// delegate void ActionMethod(string s);
public DotNet35Land()
{
Action<string> action = delegate(string s) {
if (s.Length != 5)
throw new ArgumentException("Length != 5");
};
}
and… Action
LAMBDA EXPRESSIONS
Func<string, bool> filter =
delegate(string s) {return s.Length == 5;};
var filter = (string s) => {return s.Length == 5;};
var filter = (string s) => s.Length == 5;
var filter = (s) => s.Length == 5;
var filter = s => s.Length == 5;
by Alonzo Church, 1930’s
string[] names = { "Tom", "Dick",
"Harry" };
names.Select((s, i) =>
(i + 1) + "=" + s);
1=Tom
2=Dick
3=Harry
int[] numbers = { 3, 5, 7 };
string[] words = { "three", "five",
"seven", "ignored" };
IEnumerable<string> zip =
numbers.Zip(words,
(n, w) => n + "=" + w);
3=three
5=five
7=seven
IEnumerable<Order> spanishOrders = customers
.Where(c => c.Country == "Spain")
.SelectMany(c => c.Orders);
var slowQuery =
from c in customers
from p in purchases where c.ID == p.CustomerID
select c.Name + " bought a " + p.Description;
var fastQuery =
from c in customers
join p in purchases on c.ID equals p.CustomerID
select c.Name + " bought a " + p.Description;
var easyToRead =
from c in customers
join p in purchases on c.ID equals p.CustomerID
select c.Name + " bought a " + p.Description;
var harderToRead = customers.Join (
purchases,
c => (int?)(c.ID),
p => p.CustomerID,
(c, p) => ((c.Name + " bought a ") +
p.Description)
);
public static class EnumerableExtensions
{
public static string ToCsv<T>(
this IEnumerable<T> sequence)
{
const string delimiter = ", ";
return sequence.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s + delimiter),
sb => sb.ToString()
.TrimEnd(delimiter.ToArray()));
}
}
new[] { 1, 2, 3, 5, 8, 13, 20 } => 1, 2, 3, 5, 8, 13, 20