【发布时间】:2015-03-24 21:19:57
【问题描述】:
我有 3 个数据类型如下的数组:
string[] arrID = {"111", "222", "333", "444", "555", "666", "777"};
DateTime[] arrDates = new DateTime[]
{
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 21),
new DateTime(2015, 03, 21),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20)
};
string[] arrTime = {"8:20", "8:40", "8:20", "9:10", "8:20", "9:10", "8:20"};
我已将示例元素添加到 3 个数组中,以模拟我们将在这些数组中拥有的数据类型。
每个元素中的每个索引号都包含与一条记录相关的值。
示例:每个索引为 3 的数组中的值包含构成一条记录的值。
我需要根据以下条件将这 3 个数组中的值放入以下 3 个数组中:arrNEWID、arrNEWDate 和 arrNEWTime:
- 对于每个唯一的日期和时间组合,需要向每个数组添加一个单独的元素。
- 如果唯一的日期和时间组合有多个 ID,则这些 ID 需要用逗号分隔。
3 个新数组中的预期输出
--------------------------------------------------
| index | arrNEWDate | arrNEWTime | arrNEWID |
--------------------------------------------------
| 0 | 03/20/2015 | 8:20 | 111,333,777 |
| 1 | 03/20/2015 | 8:40 | 222 |
| 2 | 03/20/2015 | 9:10 | 666 |
| 3 | 03/21/2015 | 8:20 | 555 |
| 4 | 03/21/2015 | 9:10 | 444 |
注意事项:
- 3个NEW数组的数据类型需要是string
- 输入和输出需要保持为数组。可以创建列表进行处理
这是我已经使用过的代码:
string[] arrID = { "111", "222", "333", "444", "555", "666", "777" };
DateTime[] arrDates = new DateTime[]
{
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 21),
new DateTime(2015, 03, 21),
new DateTime(2015, 03, 20),
new DateTime(2015, 03, 20)
};
string[] arrTime = { "8:20", "8:40", "8:20", "9:10", "8:20", "9:10", "8:20" };
string str_arrNEWID = "";
string str_arrNEWDate = "";
string str_arrNEWTime = "";
string[] arrNEWID = "".Split('~');
string[] arrNEWDate = "".Split('~');
string[] arrNEWTime = "".Split('~');
for (int i = 0; i <= arrID.GetUpperBound(0); i++)
{
int intExists = 0;
for (int j = 0; j <= arrNEWDate.GetUpperBound(0); j++)
{
//check if date matches for the current index being checked
if (arrNEWDate[j].ToString() == arrDates[i].Date.ToString("MM/dd/yyyy"))
{
//check if time matches for the same index
if (arrNEWTime[j].ToString() == arrTime[i].ToString())
{
//existing record
intExists = 1;
arrNEWID[j] = arrNEWID[j] + "," + arrID[i];
str_arrNEWID = string.Join("~", arrNEWID);
}
}
}
if (intExists == 0)
{
//new record
str_arrNEWDate = str_arrNEWDate + "~" + arrDates[i].Date.ToString("MM/dd/yyyy") ;
arrNEWDate = str_arrNEWDate.Split('~');
str_arrNEWTime = str_arrNEWTime + "~" + arrTime[i].ToString() ;
arrNEWTime = str_arrNEWTime.Split('~');
str_arrNEWID = str_arrNEWID + "~" + arrID[i];
arrNEWID = str_arrNEWID.Split('~');
}
}
主要的挑战是需要用来编译这段代码的编译器不支持 lambda 运算符(=>)
我需要知道:
如果有办法让我不必每次都使用临时字符串变量和拆分函数来刷新数组
如果有办法摆脱多重循环
【问题讨论】:
-
你试过什么?那段代码做了什么?这与您期望或希望它做的有什么不同?请参阅stackoverflow.com/help/how-to-ask,获取有关如何以清晰、可回答的方式提出问题的建议。
-
我已经添加了这些细节。谢谢你的时间:)
-
问题已更新。请删除或解释否决票