2010-11-03 45 views
0

大家晚上好,努力工作阈值到LINQ查询(IES)

我一直在试图找出最有效的方式做到这一点,但我未能达到。这是怎么回事......

我最终试图根据特定客户的购买习惯和给定的门槛,例如50%来确定“喜欢的客户”。 IE客户1购买了产品A,B,C,D ......客户2购买了B,C,D,E ......这两个客户都是> = 50%“相似性”,因此它们应该匹配。

我的架构是可以预期

CLIENT (1 ----- many) CLIENT_PURCHASE (1 -------many) PRODUCT 

*clientID   *clientID *prodID     *prodID 

现在我忽略的门槛,只是想找到谁购买1号客户的历史记录中的任何项目的客户。我认为我有以下两个查询工作:

var clientOneHistory = (from cp in client.Client_Purchase 
         select cp.prodID).ToList(); 

var matchedClients = (from cp in db.Client_Purchase 
         where clientOneHistory.Contains(cp.prodID) 
         select cp.Client.fullname).Distinct().ToList(); 

所以我最终的问题是,“我如何在阈值部分工作? 感谢您的时间

+0

说客户1购买A,B和客户2购买A,B,C,D他们是100%相同还是50%相同? – spender 2010-11-03 01:45:03

+0

对不起,我应该更清楚一点关于门槛。 简而言之,我想比较客户1的购买与其他人的购买。如果顾客1购买了A B,并且顾客2购买了A B C D,则在购买顾客1的100%购买时,顾客2在技术上将超过最低所需阈值50%。 总的百分比将超出客户1的购买。如果客户2只购买了A,他将是50%“喜欢”客户1.希望这足够清楚。请让我知道任何其他澄清。再次感谢各位 – dahnealdo 2010-11-03 02:00:46

回答

0

我不确定如何为您的特定情况形成这些查询。假设你想使用LINQ到SQL。相反,我将使用NorthWind数据库作为示例来做同样的事情。然后你可以在你的实现中使用这里使用的想法。我不认为完全可以使用LINQ到SQL来完成这个任务,你必须进行混合。

var threshold = 0.5M; 

// let's pick a customer id 
var myId = "VINET"; 

// get products of current customer 
var myProducts = (from c in db.Customers 
        where c.CustomerID == myId 
        join o in db.Orders on c.CustomerID equals o.CustomerID 
        join od in db.Order_Details on o.OrderID equals od.OrderID 
        select od.ProductID) 
       .Distinct() 
       .ToArray(); 

// get the products of all other customers 
var others = (from c in db.Customers 
       where c.CustomerID != myId 
       join o in db.Orders on c.CustomerID equals o.CustomerID 
       join od in db.Order_Details on o.OrderID equals od.OrderID 
       group od.ProductID by c.CustomerID into g 
       select new { CustomerID = g.Key, Products = g.Distinct() }) 
      .AsEnumerable(); 

// calculate "likeness" values for each person 
var likeness = from o in others 
       let Percent = Decimal.Divide(myProducts.Intersect(o.Products).Count(), myProducts.Length) 
       where Percent >= threshold 
       select new { o.CustomerID, Percent }; 
+0

想过之后,我想你会对最后一次查询感兴趣。 – 2010-11-03 05:01:50

+0

感谢您的建议,我喜欢解决方案。我有点意识到,当你把它分解到最低层时,我基本上比较了两个常见元素的列表,这可以用intersect()方法很好地完成。有了这些可用,肯定会使得获得百分比更加可行/高效,因为您做得很好。再次感谢 – dahnealdo 2010-11-03 14:07:47