0

我想要以下代码:

List<Tuple<string, double>> historicalDailyHigh = new List<Tuple<string, double>>();

  foreach (var item in historicalDailyHigh)
                {
                    if (item.Item1.Contains(closestPreDailyHigh.ToString()))
                    {
                        closestPreDailyHighName = item.Item1;
                    }
                }

写在一行中,类似于这一行,只有“closestPreDailyHighName”应该是一个字符串:

closestPreDailyHighName = historicalDailyHigh.Any(x => x.Item1.Contains(closestPreDailyHigh.ToString()));

有人可以给我一个关于如何做到这一点的提示吗?

4

2 回答 2

2

从技术上讲,您的代码可以重写为

 closestPreDailyHighName = historicalDailyHigh
    .LastOrDefault(item => item.Item1.Contains(closestPreDailyHigh.ToString()))
   ?.Item1 ?? closestPreDailyHighName;

注意,你没有放在break里面if,这就是最后一个满足条件的项目将被分配。如果都不item符合条件,我们不更改closestPreDailyHighName.

如果省略break是一个错字,你可以把

 closestPreDailyHighName = historicalDailyHigh
    .FirstOrDefault(item => item.Item1.Contains(closestPreDailyHigh.ToString()))
   ?.Item1 ?? closestPreDailyHighName; 

如果保证始终存在,item您可以更改FirstOrDefaultFirst

 closestPreDailyHighName = historicalDailyHigh
    .First(item => item.Item1.Contains(closestPreDailyHigh.ToString()))
    .Item1; 
于 2021-04-08T08:30:20.710 回答
0

我的解决方案现在看起来像这样:

closestPreDailyHigh = historicalDailyHigh.Min(x => x.Item2);
closestPreDailyHighName = historicalDailyHigh.First(x => x.Item1.Contains(closestPreDailyHigh.ToString())).Item1;

谢谢您的意见!

于 2021-04-08T09:54:33.107 回答