我有一个看起来像这样的课程:
public class UserAction
{
public int LogId { get; set; }
public string UserName { get; set; }
public CrudAction Action { get; set; }
public DateTime Date{ get; set; }
}
此类的目的是存储有关谁对我的 Web 应用程序中的表单进行更改的信息。在表单上,您可以打开一个模式,显示这些更改及其发生的时间。
现在,问题是表单具有自动保存功能,可以在每次更改后保存表单,这会在短时间内生成大量日志帖子,因此看起来有点混乱。当我打开模态查看日志时,它通常看起来像这样:
User User action Date and time of action
Lisa Edited 2018-05-20 09:46 AM GMT+2
Tom Edited 2018-05-18 11:18 AM GMT+2
Tom Edited 2018-05-18 11:18 AM GMT+2
Tom Edited 2018-05-18 11:18 AM GMT+2
Tom Edited 2018-05-18 11:16 AM GMT+2
Tom Edited 2018-05-18 11:15 AM GMT+2
Tom Edited 2018-05-18 11:15 AM GMT+2
Tom Edited 2018-05-18 11:15 AM GMT+2
Tom Edited 2018-05-18 10:12 AM GMT+2
Lisa Edited 2018-05-16 13.28 PM GMT+2
Lisa Posted 2018-05-16 13.25 PM GMT+2
我正在寻找一种巧妙的方法,以某种方式将同一个人在同一小时内以相同的操作生成的所有帖子分组,并且只显示最新的帖子。像这样的东西:
User User action Date and time of action
Lisa Edited 2018-05-20 09:46 AM GMT+2
Tom Edited 2018-05-18 11:18 AM GMT+2
Tom Edited 2018-05-18 10:12 AM GMT+2
Lisa Edited 2018-05-16 13.28 PM GMT+2
Lisa Posted 2018-05-16 13.25 PM GMT+2
我的应用程序是一个 angular 5 应用程序,我使用 .Net Core Web API 从 SQL 数据库获取数据。我想这的逻辑可能在 angular 应用程序或 web api 中,但也许在客户端上执行此操作更可取?
我已经尝试在 javascript 和 LINQ 中进行这项工作,但我并没有走得很远(有些东西没有在我的大脑中点击)所以任何帮助将不胜感激。
如果您永远不想显示被分组过滤掉的数据,最好过滤服务器端已经存在的数据。原因是,否则你会将不必要的数据传输到客户端,无论如何都要删除它们。这会减慢您的应用程序的速度。只传输您需要的数据。
在 Web API 控制器中,您可以使用 LINQ 的强大功能。诀窍是引入IEqualityComparer<UserAction>
实现您的要求的自定义,然后将其提供给Distinct
方法。
UserAction[] userActions = dbContext.UserActions.ToArray();
var distinctActions = userActions
.OrderByDescending(ua => ua.Date) // sort as you like here
.Distinct(new UserNameActionAndHourComparer()); // apply filter
public class UserNameActionAndHourComparer : IEqualityComparer<UserAction> {
public bool Equals(UserAction left, UserAction right){
if (left == null && right == null) {
return true;
}
if (left == null | right == null) {
return false;
}
// your equality criteria here ...
if (left.UserName == right.UserName && left.Action == right.Action) {
// implement requirement that same hour is considered equal
return left.Date.Date == right.Date.Date && left.Date.Hour == right.Date.Hour;
}
return false;
}
// if two UserActions are considered equal, they should yield the same hashcode
public int GetHashCode(UserAction ua) {
return ua.UserName.GetHashCode()
^ ua.Action.GetHashCode()
^ new DateTime(ua.Date.Year, ua.Date.Month, ua.Date.Day, ua.Date.Hour, 0, 0).GetHashCode();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句