単一のLINQクエリを使用して、次のように1次元配列を変換することは可能ですか?
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
IEnumerable<>
3つのプロパティを含む3つのオブジェクトに、3つの連続する各文字列から構築しますか?
はい、可能です。配列内のインデックスでグループ化できます。
string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
var result = source
.Select((element, index) => new { element, index })
.GroupBy(x => x.index / 3)
.Select(x => new
{
Id = x.ElementAt(0).element,
Name = x.ElementAt(1).element,
Value = x.ElementAt(2).element
}).ToList();
// at this stage the result variable will represent a list of 3 elements where
// each element is an anonymous object containing the 3 properties. You could of course
// replace the anonymous object with a model if you intend to use the result of the query
// outside of the scope of the method it is being executed in.
明らかに、この例では、エラーチェックはありません。これは、LINQクエリを実行する前に実行することを検討する可能性があることです。配列の長さは明らかに3で割り切れるはずです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加