[C#] 陣列中的資料方法簡說 | 簡化for與foreach

這次整理一篇有關陣列的資料處理方法
(比較常用的方法)
可以盡量省去使用for與foreach
有些沒列出來的就是不適合用在陣列or方法容易理解
(有些方法可能沒貼到)
[Aggregate]
//合併(累積)字串
string[] aggtest = { "abc", "def", "ghi" };
Console.WriteLine(aggtest.Aggregate((total, next) => total + next));
//output:abcdefghi
[All]
//陣列中的所有元素是否都符合指定的lambda判斷式
string[] alltest = { "abc", "bcd", "cde" };
Console.WriteLine(alltest.All(x => x.Contains("c")));
//output:true
[Any]
//陣列中的其中一個元素是否符合指定的lambda判斷式
string[] anytest = { "abc", "bcd", "cde" };
Console.WriteLine(anytest.Any(i => i == "abc"));
//output:true
//陣列中是否有任何元素
string[] anytest2 = { };
Console.WriteLine(anytest2.Any());
//output:false
[Cast]
//轉換型別
object[] casttest = { 1, 5 };
Console.WriteLine(casttest.Cast<int>().ToArray()[0]);
//output:1
[Clone]
//複製一份"新的執行個體"(不會受前一個物件影響)
string[] clonetest1 = { "Hello" };
string[] clonetest2 = clonetest1.Clone() as string[];
clonetest2[0] = "World!";
Console.WriteLine("{0} {1}",clonetest1[0],clonetest2[0]);
//output:Hello World!
[Concat]
//第二個陣列合併到第一個陣列
string[] concat1test = { "Hello" };
string[] concat2test = { "World!" };
Console.WriteLine(concat1test.Concat(concat2test).ToArray().Length);
//output:2
[Count]
//傳回陣列中的元素數目
string[] counttest = { "Hello", " World", "!" };
Console.WriteLine(counttest.Count());
//output:3
[DefaultIfEmpty]
//如果陣列沒有任何元素,就使用預設值陣列
string[] emptytest = { };
Console.WriteLine(emptytest.DefaultIfEmpty("NULL").ToArray()[0]);
//output:NULL
[Distinct]
//移除陣列中重複的元素
string[] distincttest = { "ABC", "BCD", "ABC" };
Console.WriteLine(distincttest.Distinct().ToArray().Length);
//output:2
[ElementAt、ElementAtOrDefault]
//傳回陣列中指定位置的元素
string[] elementattest = { "one", "two", "three" };
Console.WriteLine(elementattest.ElementAt(2));
//output:three
//傳回陣列中指定位置的元素,超出範圍則傳回預設值
Console.WriteLine(elementattest.ElementAtOrDefault(3));
//output:(空白)
[Except]
//比較兩個陣列,如果第二陣列元素有出現在第一陣列,則會移除掉
string[] except1test = { "A", "B", "C", "D" };
string[] except2test = { "B", "D" };
Console.WriteLine(except1test.Except(except2test)
    .Aggregate((total, next) => total + next));
//output:AC
[First、Last]
//傳回陣列第一個項目(Last為最後一個項目)
string[] firsttest = { "Hello", "World!" };
Console.WriteLine(firsttest.First());
//output:Hello
[FirstOrDefault、LastOrDefault]
//如果有判斷式並符合條件,則會傳回符合條件的後一個元素。
//參數可為空,這將傳回預設值。(同LastOrDefault)
int[] firstdeftest = { 1, 2, 3 };
Console.WriteLine(firstdeftest.FirstOrDefault(i => i > 1));
//output:2
[Intersect]
//傳回兩個陣列是否有相同的元素,有的話則傳回相同的元素
string[] intersect1test = { "A", "B", "D" };
string[] intersect2test = { "A", "B", "C" };
Console.WriteLine(intersect1test.Intersect(intersect2test)
    .Aggregate((total, next) => total + next));
//output:AB
[Max、Min]
//傳回陣列中最大的項目,文字會以進制比較,同Min
string[] maxtest = { "", "", "" };
Console.WriteLine(maxtest.Max());
//output:我
[OrderBy、OrderByDescending]
//對陣列進行遞增排序、OrderByDescending為遞減排序
int[] orderbytest = { 1, 25, 14, 3, 9, 2 };
foreach (int index in orderbytest.OrderBy(index => index))
{
    Console.Write("{0} ", index);
}
Console.WriteLine();
//output:1 2 3 9 14 25
[Reverse]
//反轉陣列
string[] reversetest = { "", "", "" };
Console.WriteLine(reversetest.Reverse().
    Aggregate((total, next) => total + next));
//output:三二一
[Select]
//修改每個元素,自訂lambda方法
string[] selecttest = { "AB", "BC", "CD" };
Console.WriteLine(selecttest.Select(text => text + "Z")
    .Aggregate((total, next) => total + next));
//output:ABZBCZCDZ
[Skip]
//略過指定的元素數量,這會從位置0開始略過
string[] skiptest = { "zero", "one", "two" };
Console.WriteLine(skiptest.Skip(2)
    .Aggregate((total, next) => total + next));
//output:two
[SkipWhile]
//如果判斷式為true,則會略過該元素
string[] skipwhiletest = { "zero", "one", "two" };
Console.WriteLine(skipwhiletest
    .SkipWhile(text => text == "zero")
    .Aggregate((total, next) => total + next));
//output:onetwo
[Take]
//取出從零開始指定數量的元素
string[] taketest = { "zero", "one", "two" };
Console.WriteLine(taketest.Take(2)
    .Aggregate((total, next) => total + next));
//output:zeroone
[TakeWhile]
//如果判斷式為true,則會取出除了它"前面的元素"
string[] takewhiletest = { "zero", "one", "two", "three" };
Console.WriteLine(takewhiletest
    .TakeWhile(text => string.Compare("two", text) != 0)
    .Aggregate((total, next) => total + next));
//output:zeroone
[ToDictionary]
//轉換為Dictionary,lambda內是要新增的Key
Package[] package = {
    new Package() { Name = "One", Index = 1 },
    new Package() { Name = "Two", Index = 2 } };
Dictionary<int, Package> packagedic = package.ToDictionary(p => p.Index);
Console.WriteLine(packagedic[1].Name);
//output:One
[Union]
//集合兩個陣列,傳回陣列中不重複的元素
string[] union1test = { "A", "B", "C" };
string[] union2test = { "B", "D", "E" };
Console.WriteLine(union1test.Union(union2test)
    .Aggregate((total, next) => total + next));
//output:ABCDE
[Where]
//過濾元素,自訂lambda方法
string[] wheretest = { "Hello", "Hey", "Enjoy", "Lol" };
Console.WriteLine(wheretest
    .Where((text) => !text.Contains("Hey"))
    .Aggregate((total, next) => total + next));
//output:HelloEenjoyLol
[Zip]
//合併兩個陣列,這會針對每個元素做合併
string[] zip1test = { "A", "B", "C" };
string[] zip2test = { "X", "Y", "Z" };
Console.WriteLine(zip1test
    .Zip(zip2test, (a, b) => a + b)
    .Aggregate((total, next) => total + next));
//output:AXBYCZ

留言