トップページに戻る
次のC#のサンプルへ
前のC#のサンプルへ
6-3 Where拡張メソッド
C#のサンプル
メソッド構文での使用例
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] ArrInt = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
IEnumerable<int> query = ArrInt.Where(A => A % 2 == 0);
foreach (int Any in query) Console.WriteLine(Any);
}
}
//出力結果
//2
//4
//6
//8
クエリ構文での使用例
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] ArrInt = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
IEnumerable<int> query = from A in ArrInt
where A % 2 == 0
select A;
foreach (int Any in query) Console.WriteLine(Any);
}
}
//出力結果
//2
//4
//6
//8
Arrayクラスでの代用案
using System;
class Program
{
static void Main()
{
int[] ArrInt = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] query = Array.FindAll<int>(ArrInt, A => A % 2 == 0);
foreach (int Any in query) Console.WriteLine(Any);
}
}
//出力結果
//2
//4
//6
//8
Listジェネリックでの代用案
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var intList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> query = intList.FindAll(A => A % 2 == 0);
foreach (int Any in query) Console.WriteLine(Any);
}
}
//出力結果
//2
//4
//6
//8
Dictionaryジェネリックでの代用案
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var intDict = new Dictionary<int, string>();
for (int I = 1; I <= 9; I++)
intDict.Add(I, string.Format("Value{0}", I));
var WillDeleteList = new List<int>();
foreach (int Any in intDict.Keys) {
if (Any % 2 == 0) continue;
WillDeleteList.Add(Any);
}
WillDeleteList.ForEach(A => intDict.Remove(A));
foreach (int Any in intDict.Keys)
Console.WriteLine("Key={0},Value={1}", Any, intDict[Any]);
//var query = intDict.Where(A => A.Key % 2 == 0);
//foreach (var Any in query)
// Console.WriteLine("Key={0},Value={1}", Any.Key, Any.Value);
}
}
//出力結果
//Key=2,Value=Value2
//Key=4,Value=Value4
//Key=6,Value=Value6
//Key=8,Value=Value8
DataTableクラスでの代用案
using System;
class Program
{
static void Main()
{
var dt = new System.Data.DataTable();
dt.Columns.Add("Key", typeof(int));
dt.Columns.Add("Value", typeof(string));
for (int I = 1; I <= 9; I++)
dt.Rows.Add(I, string.Format("Value{0}", I));
System.Data.DataRow[] FilteredSet = dt.Select("Key % 2 = 0");
foreach (var each in FilteredSet)
Console.WriteLine("Key={0},Value={1}", each["Key"], each["Value"]);
//var query = dt.Select().Where(A => Convert.ToInt32(A["Key"]) % 2 == 0);
//foreach (var each in query)
// Console.WriteLine("Key={0},Value={1}", each["Key"], each["Value"]);
}
}
//出力結果
//Key=2,Value=Value2
//Key=4,Value=Value4
//Key=6,Value=Value6
//Key=8,Value=Value8
解説