2016-08-03 73 views
1

Goodmorning,C#拆分列表简化代码

我来自Python环境并转向c#。

我正在将一个更广泛的列表分割成更窄的列表和规定的长度。

有没有办法简化下面的代码? 我的猜测是它有点慢,并没有正确遵循C#常见的编码规则。

List<object> B = new List<object>(); 
for(int i = 0; i < SD_Data.Count/314; i++) { 
    var SD_Input = SD_Data.Skip(314 * i).Take(314 * i + 313); 
    B.Add(SD_Input); 
} 

A = B; 

我发现这个有用的方式

public static IEnumerable<IEnumerable<T>> Chunk<T > (this IEnumerable<T> source, int chunksize) 
{ 
    while (source.Any()) 
    { 
    yield return source.Take(chunksize); 
    source = source.Skip(chunksize); 
    }  
} 
var z = Chunk(x, 10); 

但它确实提出了以下错误:

Error (CS1513): } expected (line 69) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 88) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 88) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 89) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 89) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 90) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 91) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 92) 
Error (CS1518): Expected class, delegate, enum, interface, or struct (line 94) 
Error (CS1001): Identifier expected (line 112) 
Error (CS1001): Identifier expected (line 114) 
Error (CS1022): Type or namespace definition, or end-of-file expected (line 115) 

我的工作从McNeel犀牛软件的蝈蝈接口上。

在此先感谢!

+0

在你的第二个代码中,'var z = Chunk(x,10);'在方法之外... – DVK

回答

1

我终于想通了删除this关键字。

此线程帮了我很多。

Working with arrays/list with C# components in Grasshopper 3D

问题有人提出,因为该方法是内部的另一种方法,这是了RunScript定义。 解决的办法是把它写下来的

// <Custom additional code> 

code here 

// <Custom additional code> 

所以结果是:

private void RunScript(List<Point3d> SrcPts, List<string> Instrument, List<object> SD_Data, List<double> XY_Angles, List<string> Octave, ref object A, ref object B) 
    { 
    B = Chunk(SD_Data, 314); 
    } 

    // <Custom additional code> 

    public static IEnumerable<IEnumerable<T>> Chunk<T > (IEnumerable<T> source, int chunksize) 
    { 
    while (source.Any()) 
    { 
     yield return source.Take(chunksize); 
     source = source.Skip(chunksize); 
    } 
    } 
    // <Custom additional code> 

感谢所有的有价值的提示。

+0

很高兴你明白了。下次请发布您的整个代码(整个方法)。它可以帮助别人帮助你。 – DaniDev

0

的语法使用该方法会是这样:

var B = SD_Data.Chunk(314); 

组块被声明为Extension Method

+0

谢谢,解决了一个问题。对于愚蠢的错误,我很抱歉,我在c#中很新手。 –

0

,如果你要调用的块方法以标准方式

public static IEnumerable<IEnumerable<T>> Chunk<T > (IEnumerable<T> source, int chunksize) 
{ 
    while (source.Any()) 
    { 
    yield return source.Take(chunksize); 
    source = source.Skip(chunksize); 
    }  
}