C#Linq可以组合吗?

编程入门 行业动态 更新时间:2024-10-10 04:27:11
本文介绍了C#Linq可以组合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个数据结构:

class Product { public string Name { get; set; } public int Count { get; set; } } var list = new List<Product>(){ { Name = "Book", Count = 40}, { Name = "Car", Count = 70}, { Name = "Pen", Count = 60}........... } // 500 product object var productsUpTo100SumCountPropert = list.Where(.....) ???? // productsUpTo100SumCountPropert output: // { { Name = "Book", Count = 40}, { Name = "Pen", Count = 60} }

我想对集合的Count属性求和,并且仅返回该属性Count sum小于或等于100的产品对象.

I want to sum the Count properties of the collection and return only products objects where that property Count sum is less than or equal to 100.

如果linq无法实现,那么我可以使用哪种更好的方法呢?

If is not possible with linq, what is a better approach that I can use?

推荐答案

从您对其他人的答案和您的要旨(链接),看来您要解决的实际上是背包问题-特别是 0/1背包问题(链接).

Judging from the comments you've left on other peoples' answers and your gist (link), it looks like what you're trying to solve is in fact the Knapsack Problem - in particular, the 0/1 Knapsack Problem (link).

这个主题的Wikipedia页面(我链接到该页面)为您提供了一个简短的动态编程解决方案.它具有伪多项式运行时间("pseudo",因为复杂度取决于您为背包(W)选择的容量.

The Wikipedia page on this topic (that I linked to) has a short dynamic programming solution for you. It has pseudo-polynomial running time ("pseudo" because the complexity depends on the capacity you choose for your knapsack (W).

在运行算法之前,一个好的预处理步骤是找到所有项目权重(w_i)的最大公分母(GCD),然后将其除以每个值.

A good preprocessing step to take before running the algorithm is to find the greatest common denominator (GCD) of all of your item weights (w_i) and then divide it out of each value.

d <- GCD({w_1, w_2, ..., w_N}) w_i' <- w_i / d //for each i = 1, 2, ..., N W' <- W / d //integer division here

然后使用修改后的权重和容量(w_i'和W')解决问题.

Then solve the problem using the modified weights and capacity instead (w_i' and W').

您在要点中使用的贪婪算法无法很好地工作.这种更好的算法非常简单,值得实施.

The greedy algorithm you use in your gist won't work very well. This better algorithm is simple enough that it's worth implementing.

更多推荐

C#Linq可以组合吗?

本文发布于:2023-06-10 18:40:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/616537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!