Last active
October 2, 2018 13:28
-
-
Save Pregum/9cb497bc2799c9339d366e11e4662c92 to your computer and use it in GitHub Desktop.
For文とLinqでのサンプルデータ作成方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Collections.Generic; | |
namespace hatenablog | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// 1. for(int i = 0; i < 10; i++){ } | |
int[] collection = new int[10]; | |
for (int i = 0; i < collection.Length; i++) | |
{ | |
collection[i] = i; | |
} | |
// 2. Enumerable.Range(0, 10); | |
IEnumerable<int> secondCollection = Enumerable.Range(0, 10).ToArray(); | |
// 3. SampleDataクラスの配列を5個作成する | |
// for文を用いた方法 | |
SampleData[] sampleDatas = new SampleData[5]; | |
for (int i = 0; i < sampleDatas.Length; i++) | |
{ | |
sampleDatas[i] = new SampleData(i, i % 2 == 0); | |
} | |
// LINQを用いた方法 | |
SampleData[] sampleDatasByLinq = Enumerable.Range(0, 5) | |
.Select(x => new SampleData(x, x % 2 == 0)) | |
.ToArray(); | |
// 4. SampleDataクラス5個の配列から各1つプロパティをまとめた配列を作成する | |
// for文を用いた方法 | |
bool[] flags = new bool[5]; | |
for (int i = 0; i < flags.Length; i++) | |
{ | |
flags[i] = sampleDatas[i].Flag; | |
} | |
// LINQを用いた方法 | |
bool[] flagsByLinq = sampleDatas.Select(x => x.Flag).ToArray(); | |
// 5. SampleDataクラス5個から1プロパティがtrueの場合のみ、取得したクラスの配列を作成する | |
// for文を用いた方法 | |
List<SampleData> sampleDatasOnlyTrue = new List<SampleData>(); | |
for (int i = 0; i < sampleDatas.Length; i++) | |
{ | |
if (sampleDatas[i].Flag == true) | |
{ | |
sampleDatasOnlyTrue.Add(sampleDatas[i]); | |
} | |
} | |
SampleData[] sampOnlyTrue = new SampleData[sampleDatasOnlyTrue.Count]; | |
for (int i = 0; i < sampOnlyTrue.Length; i++) | |
{ | |
sampOnlyTrue[i] = sampleDatasOnlyTrue[i]; | |
} | |
// LINQを用いた方法 | |
SampleData[] sampOnlyTrueByLinq = sampleDatas.Where(x => x.Flag).ToArray(); | |
} | |
} | |
/// 今回のサンプルデータ | |
public class SampleData | |
{ | |
public int Number { get; set; } | |
public bool Flag { get; set; } | |
public SampleData(int number, bool flag) | |
{ | |
this.Number = number; | |
this.Flag = flag; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment