【发布时间】:2018-01-25 22:52:05
【问题描述】:
我的程序当前从一个文件中读取一大块文本数据并将其存储到一个String[] 数组中。然后,它为每一行将其拆分为一个单独的 String[] 数组,从该数组中,我将每一行拆分并在 " " 的分隔符之后将每个字符串添加到 List,这样我就可以将每个属性相互比较.
这是我正在读取的数据。
1508405807242 1508405807141 vader HELLO
1508405807340 1508405807350 luke HELLO
1508405807378 1508405807387 luke LOST vader
1508405807467 1508405807479 luke FOUND r2d2
1508405807468 1508405807480 luke LOST leia
1508405807512 1508405807400 vader LOST luke
1508405807560 1508405807504 vader HELLO
我希望输出以控制台每个角色(luke、vader、r2d2 和 leia)的不同操作,但只输出一次。一旦最近的动作输出到控制台,我希望它移动到下一个角色。
到目前为止,这是我的所有代码:
class Program
{
static void Main(string[] args)
{
// Get data from file and
String[] lines = new String[5];
lines = System.IO.File.ReadAllLines(@"C:\Users\Ad\Desktop\data.txt");
//
char delimiter = ' ';
// Creating a new list from the DataItem class
List<DataItem> dataList = new List<DataItem>();
// Foreach loop reads in lines from String Array and populates the List with the relevant data for each property.
foreach (String line in lines)
{
String[] data = new String[5];
data = line.Split(delimiter);
dataList.Add(new DataItem()
{
// Telling the application at which index each property starts
MonitorTime = data[0],
LocalTime = data[1],
Actor = data[2],
Notification = data[3],
// If Actor2 doesn't have any data it populates the property with a null value
Actor2 = data.Length > 4 ? data[4] : null
});
}
// Orders the List so that the most recently received node is the one shown first
List<DataItem> newList = dataList.OrderByDescending(x => x.LocalTime).ToList();
// Loops through all lines and writes
foreach (var item in newList)
{
if (item.Notification.Equals("HELLO"))
{
Console.WriteLine(item.Actor + " " + "ALIVE" + " " + item.MonitorTime + " " + item.Actor + " " + item.Notification + " " + item.Actor2);
}
else if(item.Notification.Equals("LOST"))
{
Console.WriteLine(item.Actor2 + " " + "DEAD" + " " + item.MonitorTime + " " + item.Actor + " " + item.Notification + " " + item.Actor2);
}
else if (item.Notification.Equals("FOUND"))
{
Console.WriteLine(item.Actor2 + " " + "ALIVE" + " " + item.MonitorTime + " " + item.Actor + " " + item.Notification + " " + item.Actor2);
}
}
Console.ReadKey();
}
}
}
// Class to hold different List items
public class DataItem
{
public string MonitorTime { get; set; }
public string LocalTime { get; set; }
public string Actor { get; set; }
public string Notification { get; set; }
public string Actor2 { get; set; }
}
我只想显示前 4 个条目,而不是全部 7 个,谢谢。
编辑:
输出应如下所示:
vader ALIVE 1508405807560 vader HELLO
luke ALIVE 1508405807468 luke LOST leia
r2d2 ALIVE 1508405807467 luke FOUND r2d2
leia DEAD 1508405807468 luke LOST leia
如果字符串中的第 4 个属性是“HELLO”,则假定该字符是活动的。
如果它是 LOST,那么第一个角色被认为是活着的,但是第二个角色被认为是死的。
如果找到了,那么这两个角色都被认为是活着的。
输出需要从字符串中的第二个属性(本地时间戳)降序排列,但应该只显示第一个属性(监视器时间戳)
我已经正确排序了输出,所以需要做的就是显示每个角色的最新动作,但我不知道如何。
希望这是有道理的。
【问题讨论】:
-
你能显示给定输入的正确输出吗?为什么?
-
@npearson 我已经更新了我的帖子,希望你能理解它