我有一个文本文件,其中包含用户名,用户名,登录和注销时间。从这个文本文件中,我需要获取用户ID和该用户在该特定日期登录的次数。我正在Windows应用程序中使用C#(.NET)进行此操作。我尝试了这段代码,但是我将整个文本放入字符串strRead中。在该strRead中,我需要获取基于日期的用户登录数。
StreamReader strmrdr = new StreamReader("Logfiles.txt");
string strRead = strmrdr.ReadToEnd();
Username:Rajini||UserId:abc||Userlogintime:10/19/13 12:33:29 PM||UserLogoutTime:10/19/13 12:33:57 PM
Username:Rajini||UserId:abc||Userlogintime:10/19/13 12:35:29 PM||UserLogoutTime:10/19/13 12:36:57 PM
这并不是很难,并且由于您只需要基于日期和用户名的计数,因此我可能会避开许多试图完全解析格式的更复杂的解决方案。一个简单的基于正则表达式的解决方案在这里就足够了:
var loginInfo =
// Read the lines in the file, one by one
File.ReadLines(args[0])
// Get a match with appropriate groups for the individual parts
.Select(l =>
Regex.Match(l,
@"Username:(?<username>[^|]+)\|\|
UserId:(?<userid>[^|]+)\|\|
Userlogintime:(?<date>\S+)", RegexOptions.IgnorePatternWhitespace))
// Create a new object with the user name and date
.Select(m => new {
Username = m.Groups["username"].Value,
Date = DateTime.Parse(m.Groups["date"].Value, CultureInfo.GetCultureInfo("en-us"))
})
// Group by itself, that is, collapse all identical objects into the same group
.GroupBy(i => i)
// Create a new object with user name, date and count
.Select(g => new {
Username = g.Key.Username,
Date = g.Key.Date,
Count = g.Count()
});
foreach (var info in loginInfo) {
Console.WriteLine("{0} {1} {2}", info.Username, info.Date, info.Count);
}
这会在稍微扩展的数据集上为我产生以下输出:
Rajini 2013-10-19 00:00:00 2
Test 2013-10-19 00:00:00 1
Rajini 2013-10-20 00:00:00 1
Test 2013-10-20 00:00:00 3
Rajini 2013-10-21 00:00:00 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句