C# 是否已经存在任何东西来扁平化单个实例和实例数组的混合?
我刚给自己写了一个实用函数C# 是否已经存在任何东西来扁平化单个实例和实例数组的混合?,c#,C#,我刚给自己写了一个实用函数 private static IEnumerable<T> Flatten<T>(params object[] items) where T : class { return items.SelectMany(c => c is T ? new[] {c as T} : (IEnumerable<T>) c); } 为此: var lines2 = records
private static IEnumerable<T> Flatten<T>(params object[] items) where T : class
{
return items.SelectMany(c => c is T ? new[] {c as T} : (IEnumerable<T>) c);
}
为此:
var lines2 = records
.GroupBy(c => new {c.CODEID, c.DESCRIPTION})
.SelectMany(c => Flatten<string>(
string.Format(insertRecord, c.Key.CODEID, c.Key.DESCRIPTION),
c.Select(d => string.Format(insertDetail, d.CODEID, d.CODESEQ, d.DATAVALUE, d.DISPLAYVALUE)),
Environment.NewLine))
;
在我向我的代码库提交如此晦涩难懂的东西之前,我想看看我是否忽略了其他一些明显的方法来避免在上面的第一种方法中使用Concat
注意:这可能属于代码审查。。。不确定您可以使代码更简单,但更重要的是,通过创建一个方法,只需在序列的开头添加一个项目,就可以使整个过程静态键入:
public static IEnumerable<T> Prepend<T>(
this IEnumerable<T> sequence,
T item)
{
yield return item;
foreach(var current in sequence)
yield return current;
}
public static IEnumerable<T> Append<T>(
this IEnumerable<T> sequence,
T item)
{
foreach(var current in sequence)
yield return current;
yield return item;
}
您可以采用的另一种方法是编写AsSequence方法,该方法可以更有效地将项目转换为大小为1的序列
public static IEnumerable<T> AsSequence<T>(this T item)
{
yield return item;
}
也许有一个很好的理由让所有的输出都成为这样的可枚举序列,而不是标准的foreach var g分组等等,但这肯定不是给定的。我会强烈考虑用FrACH重写并将代码隐藏在迭代器块中。我不知道这是否是一个很好的理由,但是对于像从CSV文件生成数据库脚本之类的功能性任务,我越来越喜欢函数式C了。我不想发疯,试图使语言屈服于此。但看看我能做什么和不能做什么很有趣。毕竟,我想在5年后找到一份工作,那时所有有趣的.NET职位都需要F:
var lines = records
.GroupBy(c => new {c.CODEID, c.DESCRIPTION})
.SelectMany(c =>
c.Select(d =>
string.Format(insertDetail, d.CODEID, d.CODESEQ, d.DATAVALUE, d.DISPLAYVALUE))
.Prepend(string.Format(insertRecord, c.Key.CODEID, c.Key.DESCRIPaTION))
.Append(Environment.NewLine);
public static IEnumerable<T> AsSequence<T>(this T item)
{
yield return item;
}
var lines = records
.GroupBy(c => new {c.CODEID, c.DESCRIPTION})
.SelectMany(c =>
string.Format(insertRecord, c.Key.CODEID, c.Key.DESCRIPTION)
.AsSequence()
.Concat(c.Select(d =>
string.Format(insertDetail, d.CODEID, d.CODESEQ, d.DATAVALUE, d.DISPLAYVALUE)))
.Concat(Environment.NewLine.AsSequence()));