本文介绍了C#的foreach只得到不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

foreach (Logs log in _logsDutyStatusChange)
{
    string driverid = log.did;
}



我怎么会只添加不同的驱动器的ID给driverid字符串?

How would I only add distinct driver ID's to the driverid string?

感谢

推荐答案

您的代码是不正确的,现在加任何东西,它只是设置一个字符串(在循环的声明)的每个值。最终的结果将是唯一的最后一个值,这将是超出范围下面的代码反正。如果你想将它们全部追加到一个字符串,用逗号隔开,例如,试试这个:

Your code isn't adding anything right now, it's just setting a string (declared in the scope of the loop) to each value. The end result would be only the last value, and it would be out of scope to the following code anyway. If you're trying to append them all to a string, separated by commas, e.g., try this:

string driverids = string.Join(",", _logsDutyStatusChange
  .Select(item=>item.did)
  .Distinct()
  .ToArray());

这篇关于C#的foreach只得到不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 08:45