如何从LINQ合并列表创建文本文件
本文关键字:创建 文本 文件 列表 合并 LINQ | 更新日期: 2023-09-27 18:21:19
我有两个LINQ到SQL列表,我使用将它们合并到一个列表中
var mergedList = List1.Union(List2);
我认为Union命令将消除列表中的所有重复。是这样吗?无论如何,我正在尝试将合并列表的内容写入csv文件。当我试图调用中的列表时,我遇到了错误
WriteToCSVFile cf = new WriteToCSVFile(mergedList);
这就是我构建类的方式:
public WriteToCSVFile(IEnumerable<T> mergedList)
我在这里做错了什么?
顺便说一句,这是我得到的错误:
The type arguments for method 'WriteToCSVFile.WriteToCSVFile(System.Collections.Generic.IEnumerable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
如果你需要更多信息,请告诉我。提前谢谢。
您需要使类成为通用
public class WriteToCSVFile<T>
{
public WriteToCSVFile(IEnumerable<T> mergedList)
{
}
...
}
并且在调用它时指定泛型参数类型,因为泛型类型无法从构造函数推断:
var cf = new WriteToCSVFile<TheTypeOfElementsInYourList>(mergedList);
类型推理只适用于方法,因此您可以编写一个扩展方法:
public static class CsvExtensions
{
public static void WriteToCSVFile<T>(this IEnumerable<T> list)
{
...
}
}
然后:
mergedList.WriteToCSVFile();
哦,我真诚地希望你不要推出自己的CSV解析器,是吗?
匿名类型不能用作泛型方法的类型参数。
由于您的方法是泛型方法,我猜您正在传递非泛型列表。我想你的列表类型被定义为
List list1= new List();
应将其定义为
List<yourType> list1 = new List<yourType>();