csharp ASP.NET MVC和LINQ

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp ASP.NET MVC和LINQ相关的知识,希望对你有一定的参考价值。

In LINQ there are two ways to instantiate a dbcontext class:

ie :

//INSTANTIATING USING "USING"
// ONCE IT IS DONE IT WILL STOP EXISTING.
//Querying with LINQ to Entities 
using (var context = new SchoolDBEntities())
{
    var query = context.Students
                       .where(s => s.StudentName == "Bill")
                       .FirstOrDefault<Student>();
}



// INSTANTIATING INTO A VARIABLE
    // GET METHOD
        // Function : Populates Details Page and Datagrid
        // FIRST REDIRECT FROM LOGIN
        // Input : No input
        public ActionResult Details()
        {
            ViewBag.Message = "Your contact page.";
            Models.MailTrackingEntities gvbd = new Models.MailTrackingEntities();

            // LINQ QUERY ???
            var SchemeList = (from scheme in gvbd.Users select scheme).ToList();

            return View(SchemeList);
        }
        
        
        
//////////////////////////////////////////////////////////////////////
// IN LINQ THERE ARE TWO WAYS TO WRITE QUERY COMMANDS AS WELL:

  //LINQ WAY
  //Querying with LINQ to Entities 
using (var context = new SchoolDBEntities())
{
    var query = context.Students
                       .where(s => s.StudentName == "Bill")
                       .FirstOrDefault<Student>();
}
  
  
  //QUERY WAY
  using (var context = new SchoolDBEntities())
{
    var query = from st in context.Students
                where st.StudentName == "Bill"
                select st;
   
    var student = query.FirstOrDefault<Student>();
}
// Distinct: Removes duplicate elements from a collection.
// This Lambda Expression sample takes only distinct numbers from array.


static void Sample_Distinct_Lambda()
{
    int[] numbers = { 1, 2, 2, 3, 5, 6, 6, 6, 8, 9 };

    var result = numbers.Distinct();

    Debug.WriteLine("Distinct removes duplicate elements:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


static void Sample_Distinct_Linq()
{
    int[] numbers = { 1, 2, 2, 3, 5, 6, 6, 6, 8, 9 };

    var result = (from n in numbers.Distinct()
                  select n);

    Debug.WriteLine("Distinct removes duplicate elements:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


// Except: Removes all elements from one collection which exist in another collection.
//This Lambda Expression sample removes numbers from "numbers1", which exist in "numbers2".
 
 
static void Sample_Except_Lambda()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = numbers1.Except(numbers2);

    Debug.WriteLine("Except creates a single sequence from numbers1 and removes the duplicates found in numbers2:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_Except_Linq()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = (from n in numbers1.Except(numbers2)
                  select n);

    Debug.WriteLine("Except creates a single sequence from numbers1 and removes the duplicates found in numbers2:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

// 	Intersect: Takes only the elements that are shared between two collections.
// This Lambda Expression sample creates a new collection with values shared between the two arrays.

static void Sample_Intersect_Lambda()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = numbers1.Intersect(numbers2);

    Debug.WriteLine("Intersect creates a single sequence with only the duplicates:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_Intersect_Linq()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = (from n in numbers1.Intersect(numbers2)
                  select n);

    Debug.WriteLine("Intersect creates a single sequence with only the duplicates:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

// Union: Combines two collections and removes duplicate elements.
// This Lambda Expression sample removes any duplicate values between the two arrays.
static void Sample_Union_Lambda()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = numbers1.Union(numbers2);

    Debug.WriteLine("Union creates a single sequence and eliminates the duplicates:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_Union_Linq()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 3, 4, 5 };

    var result = (from n in numbers1.Union(numbers2)
                  select n);

    Debug.WriteLine("Union creates a single sequence and eliminates the duplicates:");
    foreach (int number in result)
        Debug.WriteLine(number);
}
// 	Where: Filters elements from a collection to satisfy a specified condition.
// This Lambda Expression sample finds numbers with values >= 15 and values <= 25.

static void Sample_Where_Lambda_Numbers()
{
    int[] numbers = { 5, 10, 15, 20, 25, 30 };

    var result = numbers.Where(n => n >= 15 && n <= 25);

    Debug.WriteLine("Numbers being >= 15 and <= 25:");
    foreach (var number in result)
        Debug.WriteLine(number);
}

static void Sample_Where_Linq_Numbers()
{
    int[] numbers = { 5, 10, 15, 20, 25, 30 };

    var result = from n in numbers
                 where n >= 15 && n <= 25
                 select n;

    Debug.WriteLine("Numbers being >= 15 and <= 25:");
    foreach (var number in result)
        Debug.WriteLine(number);
}

// Where: Filters elements from a collection to satisfy a specified condition.
// This Lambda Expression sample finds all persons who are 30 years or older.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

static void Sample_Where_Lambda_Objects()
{
    Person[] persons = {
        new Person { Name = "Mike", Age = 25 },
        new Person { Name = "Joe", Age = 43 },
        new Person { Name = "Nadia", Age = 31 }
    };

    var result = persons.Where(p => p.Age >= 30);

    Debug.WriteLine("Finding persons who are 30 years old or older:");
    foreach (Person person in result)
        Debug.WriteLine(String.Format("{0}: {1} years old", person.Name, person.Age));
}

static void Sample_Where_Linq_Objects()
{
    Person[] persons = {
        new Person { Name = "Mike", Age = 25 },
        new Person { Name = "Joe", Age = 43 },
        new Person { Name = "Nadia", Age = 31 }
    };

    var result = from p in persons
                 where p.Age >= 30
                 select p;

    Debug.WriteLine("Finding persons who are 30 years old or older:");
    foreach (Person person in result)
        Debug.WriteLine(String.Format("{0}: {1} years old", person.Name, person.Age));
}



// Where: Filters elements from a collection to satisfy a specified condition. Use overloaded Index to pass index.
// This Lambda Expression sample finds numbers divisible by 3 and element index >= 5.

static void Sample_Where_Lambda_Indexed()
{
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    var result = numbers.Where((n, i) => n % 3 == 0 && i >= 5);

    Debug.WriteLine("Numbers divisible by 3 and indexed >= 5:");
    foreach (var number in result)
        Debug.WriteLine(number);
}

static void Sample_Where_Linq_Indexed()
{
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    var result = from n in numbers.Select((Value, Index) => new {Value, Index})
                 where (n.Value % 3 == 0 && n.Index >= 5)
                 select n.Value;

    Debug.WriteLine("Numbers divisible by 3 and indexed >= 5:");
    foreach (var number in result)
        Debug.WriteLine(number);
}
// All: Checks if all elements in a collection satisfies a specified condition.
//This Lambda Expression sample checks whether all names in array start with letter "B".

static void Sample_All_Lambda()
{
    string[] names = { "Bob", "Ned", "Amy", "Bill" };

    var result = names.All(n => n.StartsWith("B"));

    Debug.WriteLine("Does all of the names start with the letter 'B':");
    Debug.WriteLine(result);
}


// Any: Checks if any elements in a collection satisifies a specified condition.
//This Lambda Expression sample checks whether any names in array start with the letter 'B'.

static void Sample_Any_Lambda()
{
    string[] names = { "Bob", "Ned", "Amy", "Bill" };

    var result = names.Any(n => n.StartsWith("B"));

    Debug.WriteLine("Does any of the names start with the letter 'B':");
    Debug.WriteLine(result);
}


// Contains: Checks if any elements in a collection satisifies a specified value.
//This Lambda Expression sample checks whether array of numbers contains value of 5.

static void Sample_Contains_Lambda()
{
    int[] numbers = { 1, 3, 5, 7, 9 };

    var result = numbers.Contains(5);

    Debug.WriteLine("sequence contains the value 5:");
    Debug.WriteLine(result);
}

// Select: Selects, projects and transforms elements in a collection.
// This Lambda Expression sample selects and rounds down each number in array.

static void Sample_Select_Lambda_Simple()
{
    decimal[] numbers = { 3.4M, 8.33M, 5.225M };

    var result = numbers.Select(n => Math.Floor(n));

    Debug.WriteLine("Numbers rounded down:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


static void Sample_Select_Linq_Simple()
{
    decimal[] numbers = { 3.4M, 8.33M, 5.225M };

    var result = (from n in numbers
                  select Math.Floor(n));

    Debug.WriteLine("Numbers rounded down:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


// Select: Selects, projects and transforms elements in a collection.
// This Lambda Expression sample calculates cos and sin of selected angles, and projects result into anonymously typed elements.
static void Sample_Select_Lambda_Anonymous()
{
    double[] angles = { 30D, 60D, 90D }; // Angles in radians

    var result = angles.Select(a => new { Angle = a, Cos = Math.Cos(a), Sin = Math.Sin(a) });

    Debug.WriteLine("Calculated values:");
    foreach (var res in result)
        Debug.WriteLine(String.Format("Angle {0}: Cos = {1}, Sin = {2}", res.Angle, res.Cos, res.Sin));
}


static void Sample_Select_Linq_Anonymous()
{
    double[] angles = { 30D, 60D, 90D }; // Angles in radians

    var result = from a in angles
                 select new { Angle = a, Cos = Math.Cos(a), Sin = Math.Sin(a) };

    Debug.WriteLine("Calculated values:");
    foreach (var res in result)
        Debug.WriteLine(String.Format("Angle {0}: Cos = {1}, Sin = {2}", res.Angle, res.Cos, res.Sin));
}


// Select: Selects, projects and transforms elements in a collection. Can be overloaded to get element index.
// This Lambda Expression sample selects word and element index from array.
static void Sample_Select_Lambda_Indexed()
{
    string[] words = { "one", "two", "three" };

    var result = words.Select((w, i) => new
    {
        Index = i,
        Value = w
    });

    Debug.WriteLine("Words with index and value:");
    foreach (var word in result)
        Debug.WriteLine(String.Format("Index {0} is {1}", word.Index, word.Value));
}


// SelectMany: Flattens collections into a single collection (similar to cross join in SQL).
// This Lambda Expression sample cross joins two arrays, and gets cartesian product.

static void Sample_SelectMany_Lambda()
{
    string[] fruits = { "Grape", "Orange", "Apple" };
    int[] amounts = { 1, 2, 3 };

    var result = fruits.SelectMany(f => amounts, (f, a) => new
    {
        Fruit = f,
        Amount = a
    });

    Debug.WriteLine("Selecting all values from each array, and mixing them:");
    foreach (var o in result)
        Debug.WriteLine(o.Fruit + ", " + o.Amount);
}

static void Sample_SelectMany_Linq()
{
    string[] fruits = { "Grape", "Orange", "Apple" };
    int[] amounts = { 1, 2, 3 };

    var result = from f in fruits
                 from a in amounts
                 select new { Fruit = f, Amount = a };

    Debug.WriteLine("Selecting all values from each array, and mixing them:");
    foreach (var o in result)
        Debug.WriteLine(String.Format("{0}, {1}", o.Fruit, o.Amount));
}


// Skip: Skips specified number of elements in a collection.
// This Lambda Expression sample skips first 4 words in array.


static void Sample_Skip_Lambda()
{
    string[] words = { "one", "two", "three", "four", "five", "six" };

    var result = words.Skip(4);

    Debug.WriteLine("Skips the first 4 words:");
    foreach (string word in result)
        Debug.WriteLine(word);
}


// SkipWhile: Skips elements in a collection while specified condition is met.
// This Lambda Expression sample skips words in array, as long as word has length of 3 characters.
static void Sample_SkipWhile_Lambda()
{
    string[] words = { "one", "two", "three", "four", "five", "six" };

    var result = words.SkipWhile(w => w.Length == 3);

    Debug.WriteLine("Skips words while the condition is met:");
    foreach (string word in result)
        Debug.WriteLine(word);
}

// Take: Takes specified number of elements in a collection, starting from first element.
// This Lambda Expression sample takes only 5 first numbers in array.
static void Sample_Take_Lambda()
{
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    var result = numbers.Take(5);

    Debug.WriteLine("Takes the first 5 numbers only:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

// TakeWhile: Takes elements in a collection while specified condition is met, starting from first element.
// This Lambda Expression sample takes numbers from array, while number is less than 5.
static void Sample_TakeWhile_Lambda()
{
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    var result = numbers.TakeWhile(n => n < 5);

    Debug.WriteLine("Takes numbers one by one, and stops when condition is no longer met:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


Concat: Concatenates (combines) two collections.
This Lambda Expression sample concatenates two arrays of numbers.

static void Sample_Concat_Lambda_Numbers()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 4, 5, 6 };

    var result = numbers1.Concat(numbers2);

    Debug.WriteLine("Concatenating numbers1 and numbers2 gives:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


	Concat: Concatenates (combines) two collections.
This Lambda Expression sample concatenates two arrays of strings.

static void Sample_Concat_Lambda_Strings()
{
    string[] vegetables = { "Tomato", "Cucumber", "Carrot" };
    string[] fruits = { "Apples", "Grapes", "Banana" };

    var result = vegetables.Concat(fruits);

    Debug.WriteLine("Concatinating vegetables and fruits gives:");
    foreach (string piece in result)
        Debug.WriteLine(piece);
}


	SequenceEqual: Checks whether two collections are equal. Use StringComparer.OrdinalIgnoreCase parameter to ignore case.
This Lambda Expression sample shows different methods to test for array equality.

static void Sample_SequenceEqual_Lambda()
{
    string[] words =            { "one", "two", "three" };
    string[] wordsSame =        { "one", "two", "three" };
    string[] wordsOrder =       { "two", "three", "one" };
    string[] wordsCase =        { "one", "TWO", "three" };

    var resultSame = words.SequenceEqual(wordsSame);
    var resultOrder = words.SequenceEqual(wordsOrder);
    var resultCase = words.SequenceEqual(wordsCase);
    var resultCaseIgnored = words.SequenceEqual(wordsCase, StringComparer.OrdinalIgnoreCase);

    Debug.WriteLine("SequenceEqual on two identical arrays:");
    Debug.WriteLine(resultSame);

    Debug.WriteLine("SequenceEqual on two differently ordered but otherwise identical arrays:");
    Debug.WriteLine(resultOrder);

    Debug.WriteLine("SequenceEqual on two differently cased but otherwise identical arrays:");
    Debug.WriteLine(resultCase);

    Debug.WriteLine("SequenceEqual on two differently cased but otherwise identical arrays, where case is ignored:");
    Debug.WriteLine(resultCaseIgnored);
}


// Zip: Processes two collections in parallel with func instance, and combines result into a new collection.
This Lambda Expression sample uses Zip to process two arrays in parallel, while each processed pair is summed.

static void Sample_Zip_Lambda()
{
    int[] numbers1 = { 1, 2, 3 };
    int[] numbers2 = { 10, 11, 12 };

    var result = numbers1.Zip(numbers2, (a, b) => (a * b));

    Debug.WriteLine("Using Zip to combine two arrays into one (1*10, 2*11, 3*12):");
    foreach (int number in result)
        Debug.WriteLine(number);
}
// OrderBy: Sorts a collection in ascending order.
// This Lambda Expression sample sorts array of numbers in ascending order.

static void Sample_OrderBy_Lambda_Numbers()
{
    int[] numbers = { 7, 9, 5 };

    var result = numbers.OrderBy(n => n);

    Debug.WriteLine("Ordered list of numbers:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_OrderBy_Linq_Numbers()
{
    int[] numbers = { 7, 9, 5 };

    var result = from n in numbers
                 orderby n
                 select n;

    Debug.WriteLine("Ordered list of numbers:");
    foreach (int number in result)
        Debug.WriteLine(number);
}


// OrderBy: Sorts a collection in ascending order.
// This Lambda Expression sample sorts array of dates in ascending order.

static void Sample_OrderBy_Lambda_Dates()
{
    var dates = new DateTime[] {
        new DateTime(2015, 2, 15),
        new DateTime(2015, 3, 25),
        new DateTime(2015, 1, 5)
    };

    var result = dates.OrderBy(d => d);

    Debug.WriteLine("Ordered list of dates:");
    foreach (DateTime dt in result)
        Debug.WriteLine(dt.ToString("yyyy/MM/dd"));
}

static void Sample_OrderBy_Linq_Dates()
{
    var dates = new DateTime[] {
        new DateTime(2015, 2, 15),
        new DateTime(2015, 3, 25),
        new DateTime(2015, 1, 5)
    };

    var result = from d in dates
                 orderby d
                 select d;

    Debug.WriteLine("Ordered list of dates:");
    foreach (DateTime dt in result)
        Debug.WriteLine(dt.ToString("yyyy/MM/dd"));
}

// OrderBy: Sorts a collection in ascending order.
// This Lambda Expression sample sorts array of cars by "HorsePower", in ascending order.
class Car
{
    public string Name { get; set; }
    public int HorsePower { get; set; }
}

static void Sample_OrderBy_Lambda_Objects()
{
    Car[] cars = 
        {
            new Car { Name = "Super Car", HorsePower = 215 },
            new Car { Name = "Economy Car", HorsePower = 75 },
            new Car { Name = "Family Car", HorsePower = 145 },
        };

    var result = cars.OrderBy(c => c.HorsePower);

    Debug.WriteLine("Ordered list of cars by horsepower:");
    foreach (Car car in result)
        Debug.WriteLine(String.Format("{0}: {1} horses", car.Name, car.HorsePower));
}

class Car
{
    public string Name { get; set; }
    public int HorsePower { get; set; }
}

static void Sample_OrderBy_Linq_Objects()
{
    Car[] cars = 
        {
            new Car { Name = "Super Car", HorsePower = 215 },
            new Car { Name = "Economy Car", HorsePower = 75 },
            new Car { Name = "Family Car", HorsePower = 145 },
        };

    var result = from c in cars
                 orderby c.HorsePower
                 select c;

    Debug.WriteLine("Ordered list of cars by horsepower using Query Syntax:");
    foreach (Car car in result)
        Debug.WriteLine(String.Format("{0}: {1} horses", car.Name, car.HorsePower));
}

// OrderByDescending: Sorts a collection in descending order.
// This Lambda Expression sample sorts array of names in descending order.

static void Sample_OrderByDescending_Lambda()
{
    string[] names = { "Ned", "Ben", "Susan" };

    var result = names.OrderByDescending(n => n);

    Debug.WriteLine("Descending ordered list of names:");
    foreach (string name in result)
        Debug.WriteLine(name);
}

static void Sample_OrderByDescending_Linq()
{
    string[] names = { "Ned", "Ben", "Susan" };

    var result = from n in names
                 orderby n descending
                 select n;

    Debug.WriteLine("Descending ordered list of names:");
    foreach (string name in result)
        Debug.WriteLine(name);
}


// Reverse: Reverses elements in a collection.
// This Lambda Expression sample reverts characters in array.
static void Sample_Reverse_Lambda()
{
    char[] characters = { 's', 'a', 'm', 'p', 'l', 'e' };

    var result = characters.Reverse();

    Debug.WriteLine("Characters in reverse order:");
    foreach (char character in result)
        Debug.WriteLine(character);
}

static void Sample_Reverse_Linq()
{
    char[] characters = { 's', 'a', 'm', 'p', 'l', 'e' };

    var result = (from c in characters.Reverse()
                  select c);

    Debug.WriteLine("Characters in reverse order:");
    foreach (char character in result)
        Debug.WriteLine(character);
}

// ThenBy: Use after earlier sorting, to further sort a collection in ascending order.
// This Lambda Expression sample first sorts array by string length of city capital, and then by alphabet.

static void Sample_ThenBy_Lambda()
{
    string[] capitals = { "Berlin", "Paris", "Madrid", "Tokyo", "London", 
                          "Athens", "Beijing", "Seoul" };

    var result = capitals.OrderBy(c => c.Length).ThenBy(c => c);

    Debug.WriteLine("Ordered list of capitals, first by length and then alphabetical:");
    foreach (string capital in result)
        Debug.WriteLine(capital);
}

static void Sample_ThenBy_Linq()
{
    string[] capitals = { "Berlin", "Paris", "Madrid", "Tokyo", "London", "Athens", "Beijing", "Seoul" };

    var result = (from c in capitals
                  orderby c.Length
                  select c)
                 .ThenBy(c => c);

    Debug.WriteLine("Ordered list of capitals, first by length and then alphabetical:");
    foreach (string capital in result)
        Debug.WriteLine(capital);
}

// ThenByDescending: Use after earlier sorting, to further sort a collection in descending order.
// This Lambda Expression sample first orders a list of dates by year descending, and then by month descending.

static void Sample_ThenByDescending_Lambda()
{
    var dates = new DateTime[] {
        new DateTime(2015, 3, 1),
        new DateTime(2014, 7, 1),
        new DateTime(2013, 5, 1),
        new DateTime(2015, 1, 1),
        new DateTime(2015, 7, 1)
    };

    var result = dates.OrderByDescending(d => d.Year).ThenByDescending(d => d.Month);

    Debug.WriteLine("List of dates first ordered by year descending, and then by month descending:");
    foreach (DateTime dt in result)
        Debug.WriteLine(dt.ToString("yyyy/MM/dd"));
}

static void Sample_ThenByDescending_Linq()
{
    var dates = new DateTime[] {
        new DateTime(2015, 3, 1),
        new DateTime(2014, 7, 1),
        new DateTime(2013, 5, 1),
        new DateTime(2015, 1, 1),
        new DateTime(2015, 7, 1)
    };

    var result = from d in dates
                 orderby d.Year descending, d.Month descending
                 select d;

    Debug.WriteLine("List of dates first ordered by year descending, and then by month descending:");
    foreach (DateTime dt in result)
        Debug.WriteLine(dt.ToString("yyyy/MM/dd"));
}
//GroupJoin: Groups two collections by a common key value, and is imilar to left outer join in SQL.
//This Lambda Expression sample groups collection "persons" with collection "languages" by a common key.

class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Person
{
    public int LanguageId { get; set; }
    public string FirstName { get; set; }
}

static void Sample_GroupJoin_Lambda()
{
    Language[] languages = new Language[]
    {
        new Language {Id = 1, Name = "English"},
        new Language {Id = 2, Name = "Russian"}
    };

    Person[] persons = new Person[]
    {
        new Person { LanguageId = 1, FirstName = "Tom" },
        new Person { LanguageId = 1, FirstName = "Sandy" },
        new Person { LanguageId = 2, FirstName = "Vladimir" },
        new Person { LanguageId = 2, FirstName = "Mikhail" },
    };

    var result = languages.GroupJoin(persons, lang => lang.Id, pers => pers.LanguageId, 
        (lang, ps) => new { Key = lang.Name, Persons = ps });

    Debug.WriteLine("Group-joined list of people speaking either English or Russian:");
    foreach (var language in result)
    {
        Debug.WriteLine(String.Format("Persons speaking {0}:", language.Key));

        foreach (var person in language.Persons)
        {
            Debug.WriteLine(person.FirstName);
        }
    }
}


// There is no GroupJoin() for Query Expressions in C#, but
// it has the similar "join...in...on...equals...into".
class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Person
{
    public int LanguageId { get; set; }
    public string FirstName { get; set; }
}

static void Sample_GroupJoin_Linq()
{
    Language[] languages = new Language[]
    {
        new Language {Id = 1, Name = "English"},
        new Language {Id = 2, Name = "Russian"}
    };

    Person[] persons = new Person[]
    {
        new Person { LanguageId = 1, FirstName = "Tom" },
        new Person { LanguageId = 1, FirstName = "Sandy" },
        new Person { LanguageId = 2, FirstName = "Vladimir" },
        new Person { LanguageId = 2, FirstName = "Mikhail" },
    };

    var result = from lang in languages
                 join pers in persons
                 on lang.Id
                 equals pers.LanguageId into ps
                 select new
                 {
                     Key = lang.Name,
                     Persons = ps
                 };

    Debug.WriteLine("Group joined list of people speaking either English or Russian:");
    foreach (var language in result)
    {
        Debug.WriteLine(String.Format("People speaking {0}:", language.Key));

        foreach (var person in language.Persons)
        {
            Debug.WriteLine(person.FirstName);
        }
    }
}




//Join: Joins two collections by a common key value, and is similar to inner join in SQL.
//This Lambda Expression sample joins two arrays where elements match in both.

static void Sample_Join_Lambda()
{
    string[] warmCountries = { "Turkey", "Italy", "Spain", "Saudi Arabia", "Etiobia" };
    string[] europeanCountries = { "Denmark", "Germany", "Italy", "Portugal", "Spain" };

    var result = warmCountries.Join(europeanCountries, warm => warm, european => european, (warm, european) => warm);

    Debug.WriteLine("Joined countries which are both warm and Europan:");
    foreach (var country in result) // Note: result is an anomymous type, thus must use a var to iterate.
        Debug.WriteLine(country);
}

static void Sample_Join_Linq()
{
    string[] warmCountries = { "Turkey", "Italy", "Spain", "Saudi Arabia", "Etiobia" };
    string[] europeanCountries = { "Denmark", "Germany", "Italy", "Portugal", "Spain" };

    var result = (from w in warmCountries
                  join e in europeanCountries on w equals e
                  select w);

    Debug.WriteLine("Joined countries which are both warm and European using Query Syntax:");
    foreach (var country in result)
        Debug.WriteLine(country);
}

//GroupBy: Projects elements of a collection into groups by key.
//This Lambda Expression sample splits array of numbers into two groups: one which is divisible by 10, and one which is not.

static void Sample_GroupBy_Lambda()
{
    int[] numbers = { 10, 15, 20, 25, 30, 35 };

    var result = numbers.GroupBy(n => (n % 10 == 0));

    Debug.WriteLine("GroupBy has created two groups:");
    foreach (IGrouping<bool, int> group in result)
    {
        if (group.Key == true)
            Debug.WriteLine("Divisible by 10");
        else
            Debug.WriteLine("Not Divisible by 10");

        foreach (int number in group)
            Debug.WriteLine(number);
    }
}

static void Sample_GroupBy_Linq()
{
    int[] numbers = { 10, 15, 20, 25, 30, 35 };

    var result = from n in numbers
                 group n by (n % 10 == 0) into groups
                 select groups;

    Debug.WriteLine("GroupBy has created two groups:");
    foreach (IGrouping<bool, int> group in result)
    {
        if (group.Key == true)
            Debug.WriteLine("Divisible by 10");
        else
            Debug.WriteLine("Not Divisible by 10");

        foreach (int number in group)
            Debug.WriteLine(number);
    }
}
// DefaultIfEmpty: If a collection is empty, its default value is returned. Default value depends on collection type.
// This Lambda Expression sample returns default values for each of the empty collections, while "words" array is returned as is.
static void Sample_DefaultIfEmpty_Lambda_Simple()
{
    string[] emptyStr = { };
    int[]    emptyInt = { };
    string[] words = { "one", "two", "three" };

    var resultStr = emptyStr.DefaultIfEmpty(); // Default is null for string

    var resultInt = emptyInt.DefaultIfEmpty(); // Default is 0 for int

    var resultWords = words.DefaultIfEmpty(); // Not empty, so words array is just copied

    Debug.WriteLine("resultStr has one element with a value of null:");
    Debug.WriteLine(resultStr.Count() == 1 && resultStr.First() == null);

    Debug.WriteLine("resultInt has one element with a value of 0:");
    Debug.WriteLine(resultInt.Count() == 1 && resultInt.First() == 0);

    Debug.WriteLine("resultWords has same content as words array:");
    Debug.WriteLine(resultWords.SequenceEqual(words));
}


// DefaultIfEmpty: If a collection is empty, its default value is returned. Default value depends on collection type. A default value may be specified.
// This Lambda Expression sample returns specified default value of 5 for empty array.

static void Sample_DefaultIfEmpty_Lambda_DefaultValue()
{
    int[] empty = { };

    var result = empty.DefaultIfEmpty(5);

    Debug.WriteLine("result contains one element with a value of 5:");
    Debug.WriteLine(result.Count() == 1 && result.First() == 5);
}

// Empty: Generates an empty collection (with no elements).
// 	This Lambda Expression sample creates an empty sequence of type string.
// static void Sample_Empty_Lambda()
{
    var empty = Enumerable.Empty<string>();
    // To make sequence into an array use empty.ToArray()

    Debug.WriteLine("Sequence is empty:");
    Debug.WriteLine(empty.Count() == 0);
}

// Range: Generates sequence of numeric values.
// This Lambda Expression sample generates sequence within a range from 0-10.
static void Sample_Range_Lambda()
{
    var result = Enumerable.Range(0, 10);

    Debug.WriteLine("Counting from 0 to 9:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_Range_Linq()
{
    var result = from n in Enumerable.Range(0, 10)
                 select n;

    Debug.WriteLine("Counting from 0 to 9:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

// 	Repeat: Creates a collection of repeated elements, where first argument is value to repeat, and second argument is number of times to repeat.
// This Lambda Expression sample repeats the word "Banana" 5 times.
static void Sample_Repeat_Lambda()
{
    string word = "Banana";

    var result = Enumerable.Repeat(word, 5);

    Debug.WriteLine("String is repeated 5 times:");
    foreach (string str in result)
        Debug.WriteLine(str);
}

static void Sample_Repeat_Linq()
{
    string word = "Banana";

    var result = from w in Enumerable.Repeat(word, 5)
                 select w;

    Debug.WriteLine("String is repeated 5 times:");
    foreach (string str in result)
        Debug.WriteLine(str);
}
// ElementAt: Retrieves element from a collection at specified (zero-based) index.
static void Sample_ElementAt_Lambda()
{
    string[] words = { "One", "Two", "Three" };

    var result = words.ElementAt(1);

    Debug.WriteLine("Element at index 1 in the array is:");
    Debug.WriteLine(result);
}

// ElementAtOrDefault: Retrieves element from a collection at specified (zero-based) index, but gets default value if out-of-range.
static void Sample_ElementAtOrDefault_Lambda()
{
    string[] colors = { "Red", "Green", "Blue" };

    var resultIndex1 = colors.ElementAtOrDefault(1);

    var resultIndex10 = colors.ElementAtOrDefault(10);

    Debug.WriteLine("Element at index 1 in the array contains:");
    Debug.WriteLine(resultIndex1);

    Debug.WriteLine("Element at index 10 in the array does not exist:");
    Debug.WriteLine(resultIndex10 == null);
}


// First: Retrieves first element from a collection. Throws exception if collection is empty.
/ Note: Operator First will throw an exception, if there is not at least one element in the sequence.
static void Sample_First_Lambda_Simple()
{
    string[] fruits = { "Banana", "Apple", "Orange" };

    var result = fruits.First();

    Debug.WriteLine("First element in the array is:");
    Debug.WriteLine(result);
}


// First: Retrieves first element from a collection. Throws exception if collection is empty.
static void Sample_First_Lambda_Conditional()
{
    string[] countries = { "Denmark", "Sweden", "Norway" };

    var result = countries.First(c => c.Length == 6);

    Debug.WriteLine("First element with a length of 6 characters:");
    Debug.WriteLine(result);
}


// FirstOrDefault: Retrieves first element from a collection, or default value if collection is empty.
// Note: While First() will throw an exception if array...
//       ...is empty, FirstOrDefault gracefully returns null.
static void Sample_FirstOrDefault_Lambda()
{
    string[] countries = { "Denmark", "Sweden", "Norway" };
    string[] empty = { };

    var result = countries.FirstOrDefault();

    var resultEmpty = empty.FirstOrDefault();

    Debug.WriteLine("First element in the countries array contains:");
    Debug.WriteLine(result);

    Debug.WriteLine("First element in the empty array does not exist:");
    Debug.WriteLine(resultEmpty == null);
}

// Last: Retrieves last element from a collection. Throws exception if collection is empty.
static void Sample_Last_Lambda()
{
    int[] numbers = { 7, 3, 5 };

    var result = numbers.Last();

    Debug.WriteLine("Last number in array is:");
    Debug.WriteLine(result);
}


// LastOrDefault: Retrieves last element from a collection, or default value if collection is empty.
// Note: While Last will throw an exception if array...
//       ...is empty, LastOrDefault gracefully returns null.
static void Sample_LastOrDefault_Simple()
{
    string[] words = { "one", "two", "three" };
    string[] empty = { };

    var result = words.LastOrDefault();

    var resultEmpty = empty.LastOrDefault();

    Debug.WriteLine("Last element in the words array contains:");
    Debug.WriteLine(result);

    Debug.WriteLine("Last element in the empty array does not exist:");
    Debug.WriteLine(resultEmpty == null);
}

// LastOrDefault: Retrieves last element from a collection, or default value if collection is empty.
// This Lambda Expression sample retrieves last element from "words" array having a length of 3 and 2 respectively. As no elements have a length of 2, "resultNoMatch" array gets default value (null).

// Note: While Last will throw an exception if array...
//       ...is empty, LastOrDefault gracefully returns null.
static void Sample_LastOrDefault_Conditional()
{
    string[] words = { "one", "two", "three" };

    var result = words.LastOrDefault(w => w.Length == 3);

    var resultNoMatch = words.LastOrDefault(w => w.Length == 2);

    Debug.WriteLine("Last element in the words array having a length of 3:");
    Debug.WriteLine(result);

    Debug.WriteLine("Last element in the empty array having a length of 2 does not exist:");
    Debug.WriteLine(resultNoMatch == null);
}

// Single: Retrieves only element in a collection. Throws exception if not exactly one element in collection.
// Note: Single will throw an Exception, if there is not exactly one element in the array.
static void Sample_Single_Lambda()
{
    string[] names1 = { "Peter" };
    string[] names3 = { "Peter", "Joe", "Wilma" };
    string[] empty = { };

    var result1 = names1.Single();

    Debug.WriteLine("The only name in the array is:");
    Debug.WriteLine(result1);

    try
    {
        // This will throw an exception because array contains no elements
        var resultEmpty = empty.Single();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }

    try
    {
        // This will throw an exception as well because array contains more than one element
        var result3 = names3.Single();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}


// SingleOrDefault: Retrieves only element in a collection, or default value if collection is empty.
// Note: SingleOrDefault retrieves null value if array is empty, and...
//       ...throws an exception if array contains more than one element.
static void Sample_SingleOrDefault_Lambda()
{
    string[] names1 = { "Peter" };
    string[] names3 = { "Peter", "Joe", "Wilma" };
    string[] empty = { };

    var result1 = names1.SingleOrDefault();

    var resultEmpty = empty.SingleOrDefault();

    Debug.WriteLine("The only name in the array is:");
    Debug.WriteLine(result1);

    Debug.WriteLine("As array is empty, SingleOrDefault yields null:");
    Debug.WriteLine(resultEmpty == null);

    try
    {
        // This will throw an exception as well because array contains more than one element
        var result3 = names3.SingleOrDefault();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

// AsEnumerable
// AsEnumerable: casts a collection to IEnumerable of same type.	
{
    string[] names = { "John", "Suzy", "Dave" };

    var result = names.AsEnumerable();

    Debug.WriteLine("Iterating over IEnumerable collection:");
    foreach (var name in result)
        Debug.WriteLine(name);
}


// Cast
//Cast: Casts a collection to a specified type.
// Note: The source we're casting from must contain only elements of the same type.
static void Sample_Cast_Lambda()
{
    List<string> vegetables = new List<string> { "Cucumber", "Tomato", "Broccoli" };

    var result = vegetables.Cast<string>();

    Debug.WriteLine("List of vegetables casted to a simple string array:");
    foreach (string vegetable in result)
        Debug.WriteLine(vegetable);
}

// Note: The source we're casting from must contain only elements of the same type.
static void Sample_Cast_Linq()
{
    List<string> vegetables = new List<string> { "Cucumber", "Tomato", "Broccoli" };

    var result = from v in vegetables.Cast<string>()
                 select v;

    Debug.WriteLine("List of vegetables casted to a simple string array:");
    foreach (string vegetable in result)
        Debug.WriteLine(vegetable);
}

// OfType
// OfType: Filters elements of specified type in a collection.
static void Sample_OfType_Lambda()
{
    object[] objects = { "Thomas", 31, 5.02, null, "Joey" };

    var result = objects.OfType<string>();

    Debug.WriteLine("Objects being of type string have the values:");
    foreach (string str in result)
        Debug.WriteLine(str);
}

static void Sample_OfType_Linq()
{
    object[] objects = { "Thomas", 31, 5.02, null, "Joey" };

    var result = from o in objects.OfType<string>()
                 select o;

    Debug.WriteLine("Objects being of type string:");
    foreach (string str in result)
        Debug.WriteLine(str);
}
// ToArray
// ToArray: Converts type to a new array.

static void Sample_ToArray_Lambda()
{
    int[] numbers = { 1, 2, 3, 4 };

    var result = numbers.ToArray();

    Debug.WriteLine("New array contains identical values:");
    foreach (int number in result)
        Debug.WriteLine(number);
}

static void Sample_ToArray_Linq()
{
    int[] numbers = { 1, 2, 3, 4 };

    var result = from n in numbers.ToArray<int>()
                 select n;

    Debug.WriteLine("New array contains identical values:");
    foreach (int number in result)
        Debug.WriteLine(number);
}
// ToDictionary(simple)
// ToDictionary: Converts collection into a Dictionary with Key and Value.

class English2German
{
    public string EnglishSalute { get; set; }
    public string GermanSalute { get; set; }
}

static void Sample_ToDictionary_Lambda_Simple()
{
    English2German[] english2German = 
    { 
        new English2German { EnglishSalute = "Good morning", GermanSalute = "Guten Morgen" },
        new English2German { EnglishSalute = "Good day", GermanSalute = "Guten Tag" },
        new English2German { EnglishSalute = "Good evening", GermanSalute = "Guten Abend" },
    };

    var result = english2German.ToDictionary(k => k.EnglishSalute, v => v.GermanSalute);

    Debug.WriteLine("Values inserted into dictionary:");
    foreach (KeyValuePair<string, string> dic in result)
        Debug.WriteLine(String.Format("English salute {0} is {1} in German", dic.Key, dic.Value));
}

class English2German
{
    public string EnglishSalute { get; set; }
    public string GermanSalute { get; set; }
}

static void Sample_ToDictionary_Linq_Simple()
{
    English2German[] english2German = 
    { 
        new English2German { EnglishSalute = "Good morning", GermanSalute = "Guten Morgen" },
        new English2German { EnglishSalute = "Good day", GermanSalute = "Guten Tag" },
        new English2German { EnglishSalute = "Good evening", GermanSalute = "Guten Abend" },
    };

    var result = from e in english2German.ToDictionary(k => k.EnglishSalute, v => v.GermanSalute)
                 select e;

    Debug.WriteLine("Values put into dictionary:");
    foreach (KeyValuePair<string, string> dic in result)
        Debug.WriteLine(String.Format("English salute {0} is {1} in German", dic.Key, dic.Value));
}


// ToDictionary(conditional)
// ToDictionary: Converts collection into a Dictionary with Key and Value.
static void Sample_ToDictionary_Lambda_Conditional()
{
    int[] numbers = { 1, 2, 3, 4 };

    var result = numbers.ToDictionary(k => k, v => (v % 2) == 1 ? "Odd" : "Even");

    Debug.WriteLine("Numbers labeled Odd and Even in dictionary:");
    foreach (var dic in result)
        Debug.WriteLine("Value {0} is {1}", dic.Key, dic.Value);
}

static void Sample_ToDictionary_Linq_Conditional()
{
    int[] numbers = { 1, 2, 3, 4 };

    var result = from n in numbers.ToDictionary(k => k, v => (v % 2) == 1 ? "Odd" : "Even")
                 select n;

    Debug.WriteLine("Numbers labeled Odd and Even in dictionary:");
    foreach (var dic in result)
        Debug.WriteLine("Value {0} is {1}", dic.Key, dic.Value);
}


// ToList
// ToList: Converts collection into a List.
static void Sample_ToList_Lambda()
{
    string[] names = { "Brenda", "Carl", "Finn" };

    List<string> result = names.ToList();

    Debug.WriteLine(String.Format("names is of type: {0}", names.GetType().Name));
    Debug.WriteLine(String.Format("result is of type: {0}", result.GetType().Name));
}



// ToLookup
// ToLookup: Converts a collection into a Lookup, grouped by key.
static void Sample_ToLookup_Lambda()
{
    string[] words = { "one", "two", "three", "four", "five", "six", "seven" };

    var result = words.ToLookup(w => w.Length);

    for (int i = 1; i <= 5; i++)
    {
        Debug.WriteLine(String.Format("Elements with a length of {0}:", i));
        foreach (string word in result[i])
            Debug.WriteLine(word);
    }
}




// LAMBDA STYLE

// Aggregate (simple)
private static void Sample_Aggregate_Lambda_Simple()
{
    var numbers = new int[] { 1, 2, 3, 4, 5 };

    var result = numbers.Aggregate((a, b) => a * b);

    Debug.WriteLine("Aggregated numbers by multiplication:");
    Debug.WriteLine(result);
}


// Aggregate (seed)
private static void Sample_Aggregate_Lambda_Seed()
{
    var numbers = new int[] { 1, 2, 3 };

    var result = numbers.Aggregate(10, (a, b) => a + b);

    Debug.WriteLine("Aggregated numbers by addition with a seed of 10:");
    Debug.WriteLine(result);
}


// Average
static void Sample_Average_Lambda()
{
    int[] numbers = { 10, 10, 11, 11 };

    var result = numbers.Average();

    Debug.WriteLine("Average is:");
    Debug.WriteLine(result);
}


// Count
static void Sample_Count_Lambda()
{
    string[] names = { "Peter", "John", "Kathlyn", "Allen", "Tim" };

    var result = names.Count();

    Debug.WriteLine("Counting names gives:");
    Debug.WriteLine(result);
}


// LongCount
// Use LongCount() when you expect the result to be greater than Int32.MaxValue()
static void Sample_LongCount_Lambda()
{
    // Create array which is 5 elements larger than Int32.MaxValue
    var largeArr = Enumerable.Range(0, Int32.MaxValue).Concat(Enumerable.Range(0, 5));

    Int64 result = largeArr.LongCount();

    Debug.WriteLine("Counting largeArr elements:");
    Debug.WriteLine(result);
}


// Max
static void Sample_Max_Lambda()
{
    int[] numbers = { 2, 8, 5, 6, 1 };

    var result = numbers.Max();

    Debug.WriteLine("Highest number is:");
    Debug.WriteLine(result);
}


// Min
static void Sample_Min_Lambda()
{
    int[] numbers = { 6, 9, 3, 7, 5 };

    var result = numbers.Min();

    Debug.WriteLine("Lowest number is:");
    Debug.WriteLine(result);
}


// Sum
static void Sample_Sum_Lambda()
{
    int[] numbers = { 2, 5, 10 };

    var result = numbers.Sum();

    Debug.WriteLine("Summing the numbers yields:");
    Debug.WriteLine(result);
}

以上是关于csharp ASP.NET MVC和LINQ的主要内容,如果未能解决你的问题,请参考以下文章

在不使用 LINQ 和 EF 的情况下从 ASP.NET 切换到 ASP MVC

csharp ASP.NET MVC 5表单

csharp asp.net mvc模块属性

csharp ASP.NET MVC WebViewPageExtensions

csharp ASP.NET的助手,ASP.NET MVC应用服务器端测试

csharp ASP.NET MVC - 表单输入数组