C# Linq 基于日期的加权平均值

标签 c# linq

我找到了几篇详细介绍如何基于外键执行加权平均的帖子,但我还没有找到适合我的情况的解决方案。在这里:

我有两个表,表 A 和表 B,多对多表链接它们;没有什么复杂的:

TableA
{
     A_ID,
     Other stuff
}

TableB
{
     B_ID,
     Date
     Other stuff
}

LinkAtoB
{
     A_ID,
     B_ID
}

现在是数学部分。我或多或少地尝试根据表 B 中最近关联的数量对 TableA 的结果进行加权。

因此,如果 TableA 在表中有 4 个具有以下日期的关联:

{10/23/2010, //3 days ago
10/19/2010,  //5 days ago
10/18/2010,  //6 days ago
9/13/2010}   //40ish days ago

所以这是我想对它们进行排名的方式:

我想提供以天为单位的新近度阈值,我将以 7 天为例:

因此,使用上述数据,我将分配以下值:

{10/23/2010, //7-3 = 4
10/19/2010,  //7-5 = 2
10/18/2010,  //7-6 = 1
9/13/2010}   //40ish days ago

因此该特定 TableA 条目的加权平均值为 7/3 = 2.33333。

以下是我到目前为止所拥有的或多或少的内容:

var k = from a in TableA
        group a by a.Select(x=>x.LinkAtoB.TableB)
                    .Where(x=>x.Date.CompareTo(DateTime.Now.AddDays(-7)) >= 0)
                    into g
        select g.Sum(x => DateTime.Now.Subtract(x.Date).Days) / 
        g.Sum(x => x.Length);

我想我很接近,但我知道我的小组部分是错误的。我认为其他的东西应该工作。如何修复我的代码以完成我想要的?

最佳答案

给你! :)

var k = (from b in TableB
        join bb in LinkAtoB on b.B_ID equals bb.B_ID into b_join
        from ab in b_join.DefaultIfEmpty()
        where b.B_DATE.CompareTo(DateTime.Now.AddDays(-7)) > 0
        select new {ab.A_ID, DaysAgo = (DateTime.Now - b.B_DATE).Days} into xx
        group xx by xx.A_ID into yy
        select new {yy.Key, Weighted = yy.Sum(x=> 7 - x.DaysAgo) / yy.Count()} into zz
        join a in TableA on zz.Key equals a.A_ID
        select new {a.A_ID, a.A_Other_Stuff, zz.Weighted}).ToList();

关于C# Linq 基于日期的加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029857/

相关文章:

c# - 选择节点值并选择最大值

C# Linq to XML,当 child 满足条件时获取 parent

c# - 使用反射(PrivateObject)进行测试

c# - AjaxToolkit ModalPopupExtender 不在顶部

c# - 使用通用列名将 where 子句添加到 linq 查询

c# - 编译器是否连接 LINQ where 查询?

c# - LINQ to Entities 不支持指定的类型成员 'Title'

c# - 在 UWP 中加速编译?

c# - ExecuteSqlInterpolated/ExecuteSqlRaw 参数在 asp.net core 中错误地传递到数据库

c# - 数据表 c# 中的 dataRow 上下文错误