1
这是我使用的代码的简化版本。我需要用LINQ重写它。使用LINQ重写代码
class Program
{
// Here is the ugly stuff
static void DoStuff(int[] uidArray)
{
int chunkCount = (int)Math.Ceiling(uidArray.Length/10d);
for (int i = 0; i < chunkCount; i++)
{
// calculating the remaining uids.
// this is super ugly imho, but I couldnt come up with anything better...
int remaining = (i == chunkCount - 1) ? uidArray.Length - i * 10 : 10;
int[] currentChunks = uidArray.Skip(i * 10).Take(remaining).ToArray();
string[] data = GetDataForUids(currentChunks);
foreach (string item in data)
{
Console.WriteLine(item);
}
}
}
// Call DoStuff()
static void Main(string[] args)
{
DoStuff(Enumerable.Range(1, 21).ToArray());
Console.ReadLine();
}
// This method does is not my concern
static string[] GetDataForUids(int[] uidArray)
{
var ret = new List<string>();
foreach (int uid in uidArray)
{
ret.Add("item " + uid);
}
return ret.ToArray();
}
}
什么“真正”实现执行:
- 服用的UID
- 将它们划分在较小的阵列,最多10 UID的每个部分的
int[]
- 在for循环回吐零件零件号
- 为每个部分调用
GetDataForUids
它使用数据库为了通过uid获取数据 - 个过程中
foreach
循环
因为各种“外部”变量,如chunkCount
我怎么也想不到这个东西可以使用LINQ更好的方式来写的返回的数据。它仍然有可能吗?
+1,必须承认,用在这里分组是一个漂亮的解决方案。 – driis 2009-11-07 11:24:09