c#匹配两个列表之间,然后在两个列表之间添加时间



我有两个列表和一个类

public class CommonLog
{
    public string Break { get; set; }
    public string Cart { get; set; }
    public string Length { get; set; }
}

这是列表

commonlog.Add(new CommonLog { Break = breakTimeVar, Cart = cartVar,
    Length = lengthHours });

和这样的列表2

commonlog2.Add(new CommonLog { Break = breakTimeVar2, Cart = cartVar2,
    Length = lengthHours2 });

我需要匹配的两个信息如下

列表1包含此

0016 009130 00:01:30

列表2包含此

0016 0066486 00:00:30
0016 0050093 00:00:30
0016 0063791 00:00:30

我需要匹配两个列表之间的第一个数字0016,然后从列表2列出最后一个数字00:00:30(3 x 30秒),并将总时间与列表1总时间进行比较,然后然后根据列表2等列表1

的最后数字(时间)的总数(时间)的总数做出决定。

我将如何实现?

这是一个linq解决方案,它以类似(但更紧凑的)方式汇总列表2个条目答案:

var groupedLogs = commonlog2
    .GroupBy(c => c.Break, c => TimeSpan.Parse(c.Length))
    // group logs by Break, and get the TimeSpan representation of Length
    // for each entry of the group
    .ToDictionary(g => g.Key, g => g.Aggregate(TimeSpan.Zero, (s, c) => s + c));
    // create a dictionary and aggregate each log group into sums of TimeSpans

然后,您可以迭代commonlog的每个项目,并比较结果:

foreach(var log in commonlog)
{
    TimeSpan sum;
    groupedLogs.TryGetValue(log.Break, out sum);
    if(sum == TimeSpan.Parse(log.Length))
    {
        // do something
    }
}

或一种仅获取commonlog的匹配条目(使用C#7功能)的一种衬里方法:

var matching = commonlog.Where(
    l => groupedLogs.TryGetValue(l.Break, out TimeSpan v)
         && TimeSpan.Parse(l.Length) == v);

您可以使用groupby分组单个断裂,然后循环通过聚合休息以查找匹配项。

要概括个体断裂的情况。

我建议将TimeSpan代替string用于Length

数据

var totalBreaks = new List<CommonLog>
{
    new CommonLog
    {
        Break = "0016",
        Cart = "009130",
        Length = "00:01:30"
    }
};
var individualBreaks = new List<CommonLog>
{
    new CommonLog
    {
        Break = "0016",
        Cart = "0066486",
        Length = "00:00:30"
    },
    new CommonLog
    {
        Break = "0016",
        Cart = "0050093",
        Length = "00:00:30"
    },
    new CommonLog
    {
        Break = "0016",
        Cart = "0063791",
        Length = "00:00:30"
    }
};

逻辑

//Group the individual breaks by their Break
var breakGroups = individualBreaks.GroupBy(x => x.Break);
// Loop through the aggregates
foreach (var totalBreak in totalBreaks)
{
    // Match the aggregate to the individual
    // The Key is the Break for all individual breaks in the group
    var breaks = breakGroups.FirstOrDefault(x => x.Key == totalBreak.Break);
    // Do we have a match?
    if (breaks == null)
    {
        continue;
    }
    var breakLength = TimeSpan.Parse(totalBreak.Length);
    // Add up the individual breaks with Aggregate
    var breakTotal =
        breaks
            .Aggregate(
                TimeSpan.Zero,  // Initial break is 00:00:00
                (time, b) =>    // Add each break to the initial
                    time.Add(TimeSpan.Parse(b.Length)));
    // Does the break length match the total number of breaks?
    if (breakLength == breakTotal)
    {
    }
}

相关内容

  • 没有找到相关文章

最新更新