You need to enable JavaScript to run this app. 按属性与时间间隔分组用户操作日志的实现方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

按属性与时间间隔分组用户操作日志的实现方案咨询

Solution for Grouping Duplicate UserAction Logs (Angular 5 + .NET Core WebAPI)

Hey there! Let's fix that cluttered log list once and for all. You've got two great options to handle this grouping—either on the backend (where it's more efficient) or frontend (if you need to keep raw data client-side). Here are working implementations for both:

Backend Solution (.NET Core WebAPI with LINQ)

Handling this on the server means you don't send redundant logs to the frontend, which saves bandwidth and processing time. Use LINQ to group logs by username, action type, and hour window, then pick the latest entry from each group.

// In your WebAPI controller or data access layer
public async Task<IActionResult> GetFilteredLogs()
{
    var filteredLogs = await _context.UserActions
        .GroupBy(ua => new 
        {
            ua.UserName,
            ua.Action,
            // Create a key for the start of the hour (e.g., 2024-05-20 14:00:00)
            HourStart = new DateTime(ua.Date.Year, ua.Date.Month, ua.Date.Day, ua.Date.Hour, 0, 0)
        })
        // For each group, sort by date descending and take the newest log
        .Select(g => g.OrderByDescending(ua => ua.Date).FirstOrDefault())
        .ToListAsync();

    return Ok(filteredLogs);
}

How this works:

  • The GroupBy clause groups logs using three criteria: the user's name, the CRUD action, and the exact start of the hour (truncating minutes/seconds).
  • OrderByDescending(ua => ua.Date).FirstOrDefault() grabs the most recent log from each group.
  • Entity Framework Core translates this into efficient SQL, so the grouping happens directly in the database—no extra client-side overhead.

Frontend Solution (Angular 5 with TypeScript)

If you need to keep all raw logs on the frontend but only display the filtered set, use a Map to group logs and retain the newest entry per group.

First, make sure you have your TypeScript interfaces defined (matching your C# class):

export enum CrudAction {
    Create,
    Read,
    Update,
    Delete
}

export interface UserAction {
    logId: number;
    userName: string;
    action: CrudAction;
    date: string; // Or Date, depending on how you deserialize from API
}

Then implement the filtering logic:

// Assume you've fetched logs from API into this array
userActions: UserAction[] = [];
filteredLogs: UserAction[] = [];

filterDuplicateLogs(): void {
    const logGroupMap = new Map<string, UserAction>();

    this.userActions.forEach(log => {
        // Truncate the date to the start of the hour
        const logDate = new Date(log.date);
        logDate.setMinutes(0);
        logDate.setSeconds(0);
        logDate.setMilliseconds(0);
        const hourKey = logDate.toISOString();

        // Create a unique key for the group: username + action + hour
        const groupKey = JSON.stringify({
            userName: log.userName,
            action: log.action,
            hour: hourKey
        });

        // Replace existing entry if current log is newer
        const existingLog = logGroupMap.get(groupKey);
        if (!existingLog || new Date(log.date) > new Date(existingLog.date)) {
            logGroupMap.set(groupKey, log);
        }
    });

    // Convert Map values to array and sort by date (newest first)
    this.filteredLogs = Array.from(logGroupMap.values()).sort((a, b) => 
        new Date(b.date).getTime() - new Date(a.date).getTime()
    );
}

How this works:

  • We use a Map where each key is a stringified object of the group criteria (username, action, hour start).
  • For each log, we check if its group already exists in the map. If it does, we only keep the newer log.
  • Finally, we convert the map's values to an array and sort it to show the most recent logs first.

Quick Notes

  • Prefer the backend solution if possible—it's more efficient and reduces data transfer.
  • Make sure your CrudAction enum matches exactly between C# and TypeScript (same numeric values or string names, depending on how you serialize/deserialize).
  • If your API returns dates as strings, ensure you're parsing them correctly in Angular to avoid comparison bugs.

内容的提问来源于stack exchange,提问作者MazW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:49:41