[英]Sorting and Storing in a Multidimensional Array List based on the data retrieved from a text file
我已將以下信息存儲在文本文件中。 我正在使用文件流和流讀取器對象來讀取它。 我有一個數組方法:
string[] MyArray = allText.Split(new string[]{" ",Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
這是通過拆分單詞來存儲文本文件的全部內容。
我如何做同樣的事情,並使以下數據存儲在多維數組列表中。 通過排序。
Princeton 12/12/2013 04:13PM
Leon 10/11/2013 05:13PM
Shawn 09/09/2013 04:00PM
Sandy 07/09/2012 09:00AM
Grumpy 18/09/2013 10:00AM
像在表中一樣可視化它。 所有這些數據都存儲在多維數組列表中。 名稱必須排序和存儲,日期必須排序和存儲,時間必須排序和存儲。 在每種情況下,僅接受特定格式。
這是我嘗試過的方法,但是它不斷產生錯誤,指出get和set方法沒有被標記為extern或abstract,因此必須具有主體。
using System;
using System.Collections;
using System.IO;
using System.Text;
class Planner
{ public string firstName { get; set;}
public string lastName { get; set; }
public DateTime dateTime { get; set; }
}
class exe
{
public static void Main(string[] args)
{
List<Planner> t = new List<Planner>();
StreamReader sr = new StreamReader("@cScheduler.txt"))
{
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
string[] lines = line.Split(' ').ToArray();
//add to your list
t.Add(new Test() { firstName = lines[0], lastName = lines[1], dateTime = DateTime.ParseExact("MM/dd/yyyy hh:mm:ss tt",
lines[2] + lines[3],
CultureInfo.InvariantCulture) });
}
} //Your Ordered list now t = t.OrderBy(x => x.dateTime).ToList<Planner>();
}}
我不喜歡多維數組-我將使用List
。 無論如何,它下面都有一個數組,因此您可以隨心所欲地進行操作。 ;)
List<string> lines = new List<string>();
foreach (var line in MyArray)
lines.Add(new List<string>()(line.Split(' ')); //feel free to change the .Split as needed
lines = lines.OrderBy(l => l[0]).ThenBy(l => l[1]).ThenBy(l => l[2]).ToList(); //will sort by name, then by date, then by time
在那里, lines
應包含分離和排序的數據。 請注意,排序基於字母排序,因為所有內容仍被視為string
。 如果需要使用特定的類型,則可以解析Linq查詢中的數據。
當然,您可以在此處通過適當的類或您需要的其他任何東西解析數據(到實際的string
, DateTime
和可能的TimeSpan
實例中)。
這是您發布的代碼,已更正以與您提供的示例數據一起使用:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Planner
{
public string firstName { get; set; }
public DateTime dateTime { get; set; }
}
class exe
{
public static void Main(string[] args)
{
List<Planner> t = new List<Planner>();
using (StreamReader sr = new StreamReader("Scheduler.txt"))
{
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
string[] lines = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
var planner = new Planner();
planner.firstName = lines[0];
var dateStr = String.Format("{0} {1}", lines[1], lines[2]);
var date = DateTime.ParseExact(dateStr, "dd/MM/yyyy hh:mmtt", System.Globalization.CultureInfo.InvariantCulture); //note the date format comes second. Also, in your examples days are first, months are second!
planner.dateTime = date;
t.Add(planner);
}
}
t = t.OrderBy(l => l.firstName).ThenBy(l => l.dateTime).ToList();
}
}
我不知道為什么在示例中從未給出lastName
為什么在Planner
類中需要lastName
... O_o
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.