如何将IEnumerable转换为字节数组

时间:2016-10-27 17:21:08

标签: c# arrays ienumerable

我需要将几个数组合并为一个。我发现这似乎是一个很好的方法:

IEnumerable<byte> Combine(byte[] a1, byte[] a2, byte[] a3)
{
    foreach (byte b in a1)
        yield return b;
    foreach (byte b in a2)
        yield return b;
    foreach (byte b in a3)
        yield return b;
}

但是,我对IEnumerable并不熟悉。如何将结果转换回byte[]以便我可以进一步使用它?

谢谢。

2 个答案:

答案 0 :(得分:3)

而不是迭代它们只是linq的@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationProvider myAuthenticationProvider; @Override protected void configure( HttpSecurity http ) throws Exception { // configure filters http.addFilterBefore( new MyFilter(), UsernamePasswordAuthenticationFilter.class ); // configure authentication providers http.authenticationProvider(myAuthenticationProvider); // disable csrf http.csrf().disable(); // setup security http.authorizeRequests() .anyRequest() .fullyAuthenticated() .and().httpBasic(); } }

.Concat

如果要将其作为数组返回:

var joint = a1.Concat(a2).Concat(a3);

答案 1 :(得分:2)

我这样写:

IEnumerable<T> Combine<T>(params IEnumerable<T>[] stuff)
{
    return stuff.SelectMany(a => a);
}

并合并到这样的单个数组:

var a = new byte[] { 0, 1, 2 };
var b = new byte[] { 0, 1, 2 };
var c = new List<byte> { 0, 1, 2 };

var merged = Combine(a, b, c).ToArray();

注意套牌中的小丑 - 不需要限制对数组的输入。任何数组T[]都是IEnumerable<T>,但是还有很多其他内容。

相关问题