簡體   English   中英

使用LINQ查詢實例化2D數組

[英]Instantiate 2D Array with a LINQ Query

我是C#的新手,因此需要您的幫助。

我有一個包含很多行和3個制表符分隔字段的文件。 我想閱讀每一行,從該行提取字段,然后將3個提取的值推入一個對象中。 最后,我應該得到一個對象數組。 數組的長度應等於文件中的行數。 並且文件中的所有信息都應包含在對象中。

例如檔案

abcd pqrs mnop
asdf asdf asdf
poiu poiu poiu 
xcvx xcvb rtew
: : : :
: : : :
: : : :

這是我能想到的:


類定義

Class MyClass
{
   string field1;
   string field2;
   string field3;
}

主要

String[] Content = File.ReadAllLines("file.txt");

  var query = from line in Content
              let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries)
                          select new MyClass
                                    {field1 = Parts[0],
                                     field2 = Parts[1],
                                     field3 = Parts[2],
                                     };

如何從中獲取對象的列表或IEnumerable?

您的代碼已經為您提供了IEnumerable<MyClass>值(在query變量中)。
如果需要列表,可以在其上調用ToList()

var query = (from line in Content 
          let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries) 
                      select new MyClass 
                                {field1 = Parts[0], 
                                 field2 = Parts[1], 
                                 field3 = Parts[2], 
                                 }).ToList<MyClass>();

而已。

查詢現在將是一個列表<MyClass >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM