我知道我可以使用一些 for 循环来做到这一点,但希望可以使用一些 LINQ 表达式来完成,我对 LINQ 只是模糊地熟悉,无论如何这是我的场景,我有一个包含未知数的整数列表像下面的值,列表的大小将是已知的
var numList = new List<int>() { 12, 33, 24, 63, 45, 32, 3, 18, 22, 7, 10 };
我需要提取一个包含 4 个整数的新列表,该列表将包含上述列表中的数字,但仅包含彼此相加大于 100 的数字,因此示例是...
var extractedList1 = new List<int>() { 12, 33, 24, 45 };
var extractedList2 = new List<int>() { 33, 24, 63, 32 };
显然这里有更多的组合,但我希望有一种有效的方法来实现这一点,任何帮助都会很棒。
更新 谢谢大家,Selman22 和 Rob P. 解决方案都工作得很好,并且在使用整数列表时完全符合我的需要,但是为了让事情变得更有趣,我正在尝试调整代码以使用列表一个名为 Combo 的自定义对象
public class Combo
{
public Combo(int weight, int value)
{
Weight = weight;
Value = value;
}
public int Weight { get; set; }
public int Value { get; set; }
}
在这种情况下,我会有如下所示的组合对象列表
var c1 = new Combo(3, 7);
var c2 = new Combo(4, 6);
var c3 = new Combo(2, 10);
var c4 = new Combo(3, 13);
var c5 = new Combo(3, 5);
var c6 = new Combo(2, 7);
var comboList = new List<Combo>() { c1, c2, c3, c4, c5, c6 };
每个组合对象的值将是其权重 * 值,因此 c1 为 21,c2 为 24,依此类推。在这种情况下,我需要提取 4 个 Combo 对象的列表,其中每个对象的加法都大于 100,示例如下
var extractedList1 = new List() { c1, c2, c3, c4 };
调整现有代码可能是一个简单的更改,但我目前对 LINQ 不是很熟悉,所以再次提供任何帮助都将非常有用,感谢目前为止的帮助。
最佳答案
可能这不是一种有效的方法,但它应该有效:
var numList = new List<int>() { 12, 33, 24, 63, 45, 32, 3, 18, 22, 7, 10 };
/* get all combinations including duplicates like:
12,12,12,12 - 12,12,12,34 - 12,12,12,24 and so on
then put them into an array int[] */
var combinations = from x in numList
from y in numList
from z in numList
from t in numList
select new [] {x, y, z, t};
/* eliminate the duplicates (like 12-12-12-12) and
filter them based on Sum */
var result = combinations
.Where(x => x.Sum() > 100 && x.Distinct().Count() == x.Length);
// get distinct combinations using a custom equality comparer
var distinctResults = result.Distinct(new Comparer()).ToList();
public class Comparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
return x.OrderBy(a => a).SequenceEqual(y.OrderBy(a => a));
}
public int GetHashCode(int[] obj)
{
return obj.Select(x => x.GetHashCode()).Sum();
}
}
这种from
子句的使用叫做Compound from clause
,可以很方便的得到组合,可以引用MSDN documentation还可以查看更多示例 this article来自 Eric Lippert 的文章可能会有所帮助。
关于c# - LINQ 表达式提取数字的特定数量和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23872843/