Search Results

Search found 2 results on 1 pages for 'justingreenwood'.

Page 1/1 | 1 

  • How to join two collections with LINQ

    - by JustinGreenwood
    Here is a simple and complete example of how to perform joins on two collections with LINQ. I wrote it for a friend to show him, in one simple file, the power of LINQ queries and anonymous objects. In the file below, there are two simple data classes defined: Person and Item. In the beginning of the main method, two collections are created. Note that the Item's OwnerId field reference the PersonId of a Person object. The effect of the LINQ query below is equivalent to a SQL statement looking like this: select Person.PersonName as OwnerName, Item.ItemName as OwnedItem from Person inner join Item on Item.OwnerId = Person.PersonId order by Item.ItemName desc; using System; using System.Collections.Generic; using System.Linq; namespace LinqJoinAnonymousObjects { class Program { class Person { public int PersonId { get; set; } public string PersonName { get; set; } } class Item { public string ItemName { get; set; } public int OwnerId { get; set; } } static void Main(string[] args) { // Create two collections: one of people, and another with their possessions. var people = new List<Person> { new Person { PersonId=1, PersonName="Justin" }, new Person { PersonId=2, PersonName="Arthur" }, new Person { PersonId=3, PersonName="Bob" } }; var items = new List<Item> { new Item { OwnerId=1, ItemName="Armor" }, new Item { OwnerId=1, ItemName="Book" }, new Item { OwnerId=2, ItemName="Chain Mail" }, new Item { OwnerId=2, ItemName="Excalibur" }, new Item { OwnerId=3, ItemName="Bubbles" }, new Item { OwnerId=3, ItemName="Gold" } }; // Create a new, anonymous composite result for person id=2. var compositeResult = from p in people join i in items on p.PersonId equals i.OwnerId where p.PersonId == 2 orderby i.ItemName descending select new { OwnerName = p.PersonName, OwnedItem = i.ItemName }; // The query doesn't evaluate until you iterate through the query or convert it to a list Console.WriteLine("[" + compositeResult.GetType().Name + "]"); // Convert to a list and loop through it. var compositeList = compositeResult.ToList(); Console.WriteLine("[" + compositeList.GetType().Name + "]"); foreach (var o in compositeList) { Console.WriteLine("\t[" + o.GetType().Name + "] " + o.OwnerName + " - " + o.OwnedItem); } Console.ReadKey(); } } } The output of the program is below: [WhereSelectEnumerableIterator`2] [List`1] [<>f__AnonymousType1`2] Arthur - Excalibur [<>f__AnonymousType1`2] Arthur - Chain Mail

    Read the article

  • C#, Delegates and LINQ

    - by JustinGreenwood
    One of the topics many junior programmers struggle with is delegates. And today, anonymous delegates and lambda expressions are profuse in .net APIs.  To help some VB programmers adapt to C# and the many equivalent flavors of delegates, I walked through some simple samples to show them the different flavors of delegates. using System; using System.Collections.Generic; using System.Linq; namespace DelegateExample { class Program { public delegate string ProcessStringDelegate(string data); public static string ReverseStringStaticMethod(string data) { return new String(data.Reverse().ToArray()); } static void Main(string[] args) { var stringDelegates = new List<ProcessStringDelegate> { //========================================================== // Declare a new delegate instance and pass the name of the method in new ProcessStringDelegate(ReverseStringStaticMethod), //========================================================== // A shortcut is to just and pass the name of the method in ReverseStringStaticMethod, //========================================================== // You can create an anonymous delegate also delegate (string inputString) //Scramble { var outString = inputString; if (!string.IsNullOrWhiteSpace(inputString)) { var rand = new Random(); var chs = inputString.ToCharArray(); for (int i = 0; i < inputString.Length * 3; i++) { int x = rand.Next(chs.Length), y = rand.Next(chs.Length); char c = chs[x]; chs[x] = chs[y]; chs[y] = c; } outString = new string(chs); } return outString; }, //========================================================== // yet another syntax would be the lambda expression syntax inputString => { // ROT13 var array = inputString.ToCharArray(); for (int i = 0; i < array.Length; i++) { int n = (int)array[i]; n += (n >= 'a' && n <= 'z') ? ((n > 'm') ? 13 : -13) : ((n >= 'A' && n <= 'Z') ? ((n > 'M') ? 13 : -13) : 0); array[i] = (char)n; } return new string(array); } //========================================================== }; // Display the results of the delegate calls var stringToTransform = "Welcome to the jungle!"; System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("String to Process: "); System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.WriteLine(stringToTransform); stringDelegates.ForEach(delegatePointer => { System.Console.WriteLine(); System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("Delegate Method Name: "); System.Console.ForegroundColor = ConsoleColor.Magenta; System.Console.WriteLine(delegatePointer.Method.Name); System.Console.ForegroundColor = ConsoleColor.Cyan; System.Console.Write("Delegate Result: "); System.Console.ForegroundColor = ConsoleColor.White; System.Console.WriteLine(delegatePointer(stringToTransform)); }); System.Console.ReadKey(); } } } The output of the program is below: String to Process: Welcome to the jungle! Delegate Method Name: ReverseStringStaticMethod Delegate Result: !elgnuj eht ot emocleW Delegate Method Name: ReverseStringStaticMethod Delegate Result: !elgnuj eht ot emocleW Delegate Method Name: b__1 Delegate Result: cg ljotWotem!le une eh Delegate Method Name: b__2 Delegate Result: dX_V|`X ?| ?[X ]?{Z_X!

    Read the article

1