using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
int[] numbers = { 5, 4, 1};
string[] strings = { "zero", "one", "two"};
var digitOddEvens =
from n in numbers
select new { Digit = strings[n], Even = (n % 2 == 0) };
foreach (var d in digitOddEvens) {
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
}
}
Software Development
software development notes, main category for Cs, Java, and other programming experiences.
Select with Anonymous Types: prints uppercase and lowercase versions of each string in an input array
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
string[] words = { "Abc", "aBc", "AAA" };
var upperLowerWords =
from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
foreach (var ul in upperLowerWords) {
Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
}
}
}
Transformation: link two array.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class MainClass {
public static void Main() {
int[] numbers = { 5, 4, 1};
string[] strings = { "zero", "one", "two"};
var textNums =
from n in numbers
select strings[n];
Console.WriteLine("Number strings:");
foreach (var s in textNums) {
Console.WriteLine(s);
}
}
}
Use LINQ to query characters in a string
using System;
using System.Collections.Generic;
using System.Linq;
static class TestString {
static void Main() {
var count =
"abc 8"
.Where(c => !Char.IsLetter(c))
.Count();
Console.WriteLine(count);
}
}
Use LINQ with Dictionary
using System;
using System.Collections.Generic;
using System.Linq;
static class TestDictionary {
static void Main() {
Dictionary<int, string> frenchNumbers;
frenchNumbers = new Dictionary<int, string>();
frenchNumbers.Add(0, "zero");
frenchNumbers.Add(1, "one");
frenchNumbers.Add(2, "two");
frenchNumbers.Add(3, "three");
frenchNumbers.Add(4, "four");
var evenFrenchNumbers =
from entry in frenchNumbers
where (entry.Key % 2) == 0
select entry.Value;
}
}
Select array item by type
using System;
using System.Linq;
static class TestArray {
static void Main() {
Object[] array = { "String", 12, true, 'a' };
var types =
array
.Select(item => item.GetType().Name)
.OrderBy(type => type);
}
}
Query Reuse
using System;
using System.Linq;
static class QueryReuse {
static double Square(double n) {
Console.WriteLine(“Computing Square(” + n + “)…”);
return Math.Pow(n, 2);
}
public static void Main() {
int[] numbers = { 1, 2, 3 };
var query =
from n in numbers
select Square(n);
foreach (var n in query)
Console.WriteLine(n);
for (int i = 0; i < numbers.Length; i++) numbers[i] = numbers[i] + 10; foreach (var n in query) Console.WriteLine(n); } } [/csharp]