Chủ Nhật, 24 tháng 2, 2008

Những Ví Dụ Cơ Bản Trong LINQ

Đây là các ví dụ cơ bản tường gặp trong quá trình phát triển ứng dụng. Như lấy độ dài chuổi, lấy một phần tử bất kỳ trong mãng dữ liệu, tổng số phần tử trong mãng ....

static string[] presidents =
       {
           "Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",
           "Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",
           "Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",
           "Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",
           "Monroe", "Nixon", "Pierce", "Polk", "Reagan", "Roosevelt", "Taft",
           "Taylor", "Truman", "Tyler", "Van Buren", "Washington", "Wilson"
       };
       static string[] strings = { "one", "two", null, "three" };
       static string[] numbers = { "0042", "010", "9", "27" };

       static void Main(string[] args)
       {
           //All Prototype Where Every Element Causes the Predicate to Return True
           bool all = presidents.All(s => s.Length > 3);
           Console.WriteLine(all);

           //First Contains Prototype Where No Element Matches the Specified Value
           bool contains = presidents.Contains("Rattz");
           Console.WriteLine(contains);

           //The First Count Prototype
           int fcount = presidents.Count();
           Console.WriteLine(fcount);

           //The Second Count Prototype
           int scount = presidents.Count(s => s.StartsWith("J"));
           Console.WriteLine(scount);

           //An Example of the Second Min Prototype
           string minName = presidents.Min();
           Console.WriteLine(minName);

           //An Example of the Second Max Prototype
           string maxName = presidents.Max();
           Console.WriteLine(maxName);

           //A Query Using the Standard Dot Notation Syntax
           IEnumerable sequence = presidents.Where(n => n.Length < 6).Select(n => n);
           foreach (string name in sequence)            
               Console.WriteLine("{0}", name);            

           //The Equivalent Query Using the Query Expression Syntax
           IEnumerable sequence1 = from n in presidents where n.Length < 6 select n;
           foreach (string name in sequence1)            
               Console.WriteLine("{0}", name);

           //A Simple LINQ to Objects Query
           string president = presidents.Where(p => p.StartsWith("Lin")).First();
           Console.WriteLine(president);

           //A Trivial Sample Query
           IEnumerable items = presidents.Where(p => p.StartsWith("A"));
           foreach (string item in items)
               Console.WriteLine(item);

           //A Trivial Sample Query with an Intentionally Introduced Exception
           IEnumerable items1 = presidents.Where(s => Char.IsLower(s[4]));
           Console.WriteLine("After the query.");
           foreach (string item in items1)
               Console.WriteLine(item);

           // Create an array of ints.
           int[] ints = new int[] { 1, 2, 3, 4, 5, 6 };
           // Declare our delegate.
           Func GreaterThanTwo = i => i > 2;
           // Perform the query ... not really. Don't forget about deferred queries!!!
           IEnumerable intsGreaterThanTwo = ints.Where(GreaterThanTwo);
           // Display the results.
           foreach (int i in intsGreaterThanTwo)
               Console.WriteLine(i);

           //Another Example of the First Select Prototype
           var nameObjs = presidents.Select(p => new { p, p.Length });
           foreach (var item in nameObjs)
               Console.WriteLine(item);

           //A Third Example of the First Select Prototype
           var nameObjs1 = presidents.Select(p => new { LastName = p, Length = p.Length });
           foreach (var item in nameObjs1)
               Console.WriteLine("{0} is {1} characters long.", item.LastName, item.Length);

           //An Example of the Second Select Prototype
           var nameObjs2 = presidents.Select((p, i) => new { Index = i, LastName = p });
           foreach (var item in nameObjs2)
               Console.WriteLine("{0}. {1}", item.Index + 1, item.LastName);

           //An Example of the First SelectMany Prototype
           IEnumerable chars = presidents.SelectMany(p => p.ToArray());
           foreach (char ch in chars)
               Console.WriteLine(ch);

           //An Example of the Second SelectMany Prototype
           IEnumerable chars1 = presidents.SelectMany((p, i) => i < 5 ? p.ToArray() : new char[] { });
           foreach (char ch in chars1)
               Console.WriteLine(ch);

           //A More Complex Example of the First SelectMany Prototype
           Employee[] employees = Employee.GetEmployeesArray();
           EmployeeOptionEntry[] empOptions = EmployeeOptionEntry.GetEmployeeOptionEntries();
           var employeeOptions = employees.SelectMany(e => empOptions.Where(eo => eo.id == e.id).Select(eo => new
           {
               id = eo.id,
               optionsCount = eo.optionsCount
           }));
           foreach (var item in employeeOptions)
               Console.WriteLine(item);
         
           //An Example of the Only Take Prototype
           IEnumerable items2 = presidents.Take(5);
           foreach (string item in items2)
               Console.WriteLine(item);

           //Another Example of the Take Prototype
           IEnumerable chars2 = presidents.Take(5).SelectMany(s => s.ToArray());
           foreach (char ch in chars2)
               Console.WriteLine(ch);

           //An Example of Calling the First TakeWhile Prototype
           IEnumerable items3 = presidents.TakeWhile(s => s.Length < 10);
           foreach (string item in items3)
               Console.WriteLine(item);

           //An Example of Calling the Second TakeWhile Prototype
           IEnumerable items4 = presidents.TakeWhile((s, i) => s.Length < 10 && i < 5);
           foreach (string item in items4)
               Console.WriteLine(item);

           //An Example of the Only Skip Prototype
           IEnumerable items5 = presidents.Skip(1);
           foreach (string item in items5)
               Console.WriteLine(item);

           //An Example Calling the First SkipWhile Prototype
           IEnumerable items6 = presidents.SkipWhile(s => s.StartsWith("A"));
           foreach (string item in items6)
               Console.WriteLine(item);

           //An Example of Calling the Second SkipWhile Prototype
           IEnumerable items7 = presidents.SkipWhile((s, i) => s.Length > 4 && i < 10);
           foreach (string item in items7)
               Console.WriteLine(item);

           //An Example Calling the Only Concat Prototype
           IEnumerable items8 = presidents.Take(5).Concat(presidents.Skip(5));
           foreach (string item in items8)
               Console.WriteLine(item);

           //An Example Performing Concatention with an Alternative to Using the Concat Operator
           IEnumerable items9 = new[] {presidents.Take(5),presidents.Skip(5)}.SelectMany(s => s);
           foreach (string item in items9)
               Console.WriteLine(item);

           //An Example Calling the First ThenBy Prototype
           IEnumerable items10 = presidents.OrderBy(s => s.Length).ThenBy(s => s);
           foreach (string item in items10)
               Console.WriteLine(item);

           /*//An Example Calling the Second OrderBy Prototype
           MyVowelToConsonantRatioComparer myComp = new MyVowelToConsonantRatioComparer();
           IEnumerable namesByVToCRatio = presidents.OrderBy((s => s), myComp);
           foreach (string item in namesByVToCRatio)
           {
               int vCount = 0;
               int cCount = 0;

               myComp.GetVowelConsonantCount(item, ref vCount, ref cCount);
               double dRatio = (double)vCount / (double)cCount;
               Console.WriteLine(item + " - " + dRatio + " - " + vCount + ":" + cCount);
           }*/
       }

       //Converting an Array of Strings to Integers
       private static void ConvertingStringToIntegers()
       {           
           //Converting an Array of Strings to Integers
           int[] nums = numbers.Select(s => Int32.Parse(s)).ToArray();

           //Converting an Array of Strings to Integers and Sorting It
           int[] numsort = numbers.Select(s => Int32.Parse(s)).OrderBy(s => s).ToArray();
       }

       //Query with Intentional Exception Deferred Until Enumeration

   }


Ví dụ sắp xếp theo kiểu Datetime :

List.OrderByDescending(m => m.CreatedDate , new DateTimeComparer());

Code class DateTimeComparer:

private class DateTimeComparer : IComparer
   {
       #region IComparer Members

       int IComparer.Compare(string x, string y)
       {
           DateTime xDate = DateTime.MinValue;
           DateTime yDate = DateTime.MinValue;
           if (!string.IsNullOrEmpty(x))
               xDate = DateTime.Parse(x, new System.Globalization.CultureInfo("en-US"));
           if (!string.IsNullOrEmpty(y))
               yDate = DateTime.Parse(y, new System.Globalization.CultureInfo("en-US"));

           return (Comparer.Default.Compare(xDate, yDate));
       }
       #endregion
   }
 

Ngoài ra Linq còn rất nhiều tính khả dụng. Ví dụ phức tạp dưới đây về sort ma trận.

public static void TestSortMatrix()
       {
           List source1 = new List() { "aa5", "aa6","aa1", "aa2", "aa3", "aa4"  };
           List source2 = new List() { "bb1", "bb2", "bb3", "bb4", };
           List source3 = new List() { "cc1", "cc2", "cc3", "cc4", "cc5" };
           List source4 = new List() { "dd1", "dd2", "dd5", "dd6", "dd3", "dd4"  };
           List> source = new List>();
           source.Add(source1);
           source.Add(source2);
           source.Add(source3);
           source.Add(source4);

           List> listAll = source.SelectMany(
               (it) => it.Select((t, i) => new { t, i })).GroupBy(z => z.i).Select(
               g => g.Select(z => z.t).ToList()).ToList();

       }


DangTrung.

Không có nhận xét nào:

Đăng nhận xét