Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从数据库中选择一个或多个随机元素,这些元素的总和达到特定的数量_C#_Linq_Asp.net Mvc 4 - Fatal编程技术网

C# 如何从数据库中选择一个或多个随机元素,这些元素的总和达到特定的数量

C# 如何从数据库中选择一个或多个随机元素,这些元素的总和达到特定的数量,c#,linq,asp.net-mvc-4,C#,Linq,Asp.net Mvc 4,在安装了Entity Framework的MVC4应用程序中,我有一个模型,它有一个产品,它有一个属性金额(十进制)。当用户给出金额时,我希望从数据库中为该特定金额选择一个或多个随机产品(并通过方法将其添加到购物车) public ActionResult AddRandomProducts(十进制金额) { var r=新的随机变量(); var products=db.products.Where(p=>p.Price,因为您已经从数据库中加载了所有产品(.ToList()),一个简单的wh

在安装了Entity Framework的MVC4应用程序中,我有一个模型,它有一个
产品
,它有一个属性
金额
(十进制)。当用户给出金额时,我希望从数据库中为该特定金额选择一个或多个随机产品(并通过方法将其添加到购物车)

public ActionResult AddRandomProducts(十进制金额)
{
var r=新的随机变量();

var products=db.products.Where(p=>p.Price,因为您已经从数据库中加载了所有产品(
.ToList()
),一个简单的while循环就足够了。@alexn你能解释一下怎么做吗?我的困难是它可以是一个或多个产品,并且不能保证找到解决方案。还有没有一种方法可以在不使用
ToList()
的情况下更有效
在查询中立即加载数据库中与筛选匹配的所有内容。执行所需计算的逻辑将有助于筛选产品。只要你不做太多的“魔术”,它应该很容易转换为SQL。在我看来,这就像背包问题()@KarelFrajtak我认为你是对的。:-)我会看看他们的算法是否简单。
public ActionResult AddRandomProducts(decimal amount)
{
    var r = new Random();
    var products = db.Products.Where(p => p.Price <= amount).ToList();

    // Get the first random product
    var firstProduct = products.ElementAt(r.Next(1, products.Count));

    var otherProducts = ?????????
    //?? select one more more random products that fill the specific amount (if 
         possible, and if not to closest one that is)
    //??

    var otherProducts = new List<Product>();
    User user = db.Users.Find((int)db.GetCurrentUserId());

    foreach (var p in otherProducts)
    {
        user.AddProductToCart(p, date.Date);
    }

    db.SaveChanges();

    return Json(new { success = true });

}