繁体   English   中英

如何避免多个循环与每个数组项进行比较

[英]How to avoid multiple loops for comparison with each array item

我有一个包含客户信用额度的数组,例如 [28,32,63] 和一个包含项目值示例 [48,35] 的数组。 现在只有信用额度为 63 的客户可以购买 48 或 35 的食品,而信用额度为 28 和 32 的第一个或第二个客户都不能购买任何物品。 我可以比较项目并使用 for 循环然后找到计数例如。

int[] custCredit={28,32,63}; 
int[] ItemVal={48,35};
Dictionary<string,bool> objDict=new Dictionary<string,bool>();
for(int n=1;n<=custCredit.Length;n++)
   {
    for(int m=1;m<=ItemVal.Length;m++)
    {
      if(n>=m)
      {
           objDict.Add(n.ToString()+m.ToString(),true);
      };
    }
   }

现在我可以在字典中找到所有具有 true 的值,以找出他们可以购买的最大客户和物品数量。 现在是否可以只用一个循环来做到这一点?

使用 Linq;

int[] custCredit = { 28, 32, 63 };
int[] ItemVal = { 48, 35 };
var result = custCredit.SelectMany((c, cidx) => ItemVal.Where(i => c >= i).Select((i, iidx) => $"{cidx}{iidx}"));

如果您需要它作为字典,则为 true:

result.ToDictionary(k => k, v => true)

除了@user3104267 答案中的语法,您还可以写成:

int[] custCredit = { 28, 32, 63 };
int[] ItemVal = { 48, 35 };

var results =
    from credit in custCredit
    from item in ItemVal
    where credit >= item
    select credit.ToString() + " can buy " + item.ToString();

foreach (var r in results) Console.WriteLine(r);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM