The document discusses several C# concepts including object initializers, anonymous types, extension methods, delegates, lambda expressions, and LINQ. It shows examples of initializing a student object and list with object initializers. It defines extension methods to encrypt and decrypt strings and calls them on a sample string. It demonstrates using delegates and lambda expressions to sort an integer array in ascending and descending order. Finally, it provides examples of LINQ queries on an integer array to select even numbers using the from, where, and select clauses.
3. Anonymous Types
var variableTypeAnonyme = new { FirstName = "Flavien", Age = 23};
var variableTypeAnonyme = new { DateOfBirth = new DateTime(1984, 11, 15) };
var variableTypeAnonyme = 12;
var variableTypeAnonyme = "Flavien";
4. Extension methods
public static class Encodage
{
public static string Crypte(string chaine)
{
return
Convert.ToBase64String(Encoding.Default.GetBytes(chaine));
}
public static string Decrypte(string chaine)
{
return
Encoding.Default.GetString(Convert.FromBase64String(chaine));
}
}
10. public class TrieurDeTableau
{
[…Code supprimé pour plus de clarté…]
public void DemoTri(int[] tableau)
{
DelegateTri tri = TriAscendant;
tri(tableau);
//affichage
tri = TriDescendant;
tri(tableau);
//affichage
}}
11. Using delegates
static void Main(string[] args)
{
int[] tableau = new int[] { 4, 1,10, 8, 5 };
new TrieurDeTableau().DemoTri(tableau);
}
13. Delegate to lambda
DelegateTri tri = delegate(int[] leTableau)
{
Array.Sort(leTableau);
};
DelegateTri tri = (leTableau) =>
{
Array.Sort(leTableau);
};
14. Lambda
List<int> list = new List<int>(new int[] { 2, -5, 45, 5 });
var positiveNumbers = list.FindAll((int i) => i > 0);
LINQ
From source
Where condition
Select variable
15. LINQ
class IntroToLINQ{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}}}
16. int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;
int evenNumCount = evenNumQuery.Count();
17. List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();
// or like this:
// numQuery3 is still an int[]
var numQuery3 =
(from num in numbers
where (num % 2) == 0
select num).ToArray();