gpt4 book ai didi

c# - 从 csv 文件结构生成 c# 模型类

转载 作者:太空狗 更新时间:2023-10-29 22:30:57 24 4
gpt4 key购买 nike

这里的目标是在输入 csv 文件后,一个神奇的工具会输出带有 csv 字段的 c# 类。让我们看一个例子。

输入 myFile.csv:

Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar

输出myFile.cs

public class myFile
{
public string Year;
public string Make;
public string Model;
}

因此,我唯一需要修复的是属性的类型。之后我会使用这个类和 FileHelpers 来读取 csv 文件。稍后它将映射到 EntityFramework 类(使用 AutoMapper)并保存到数据库。

实际上,https://csv2entity.codeplex.com/看起来正在做我需要的,但它就是行不通——我安装了它,但我的 Visual Studio 中没有任何变化,没有出现新模板。这个项目完全死了。打开源代码并...决定也许我会在 stackoverflow 中问这个问题 :)

FileHelpers 只有一个简单的向导,允许您手动添加字段。但我有 50 个字段,这不是我最后一次需要这样做,所以这里首选自动化解决方案。

我相信这个问题已经解决了很多次,有什么帮助吗?

最佳答案

谢谢贝德福德,我拿了你的代码并添加了三件事:

  • 它删除对属性名称无效的符号。例如“订单号”将成为“OrderNo”属性。
  • 能够添加属性和类属性。在我的例子中,我需要 [DelimitedRecord(",")] 和 [FieldOptional()],因为我使用的是 FileHelpers。
  • 有些列没有名称,因此它会自行生成名称。命名约定为 Column10、Column11 等。

最终代码:

public class CsvToClass
{
public static string CSharpClassCodeFromCsvFile(string filePath, string delimiter = ",",
string classAttribute = "", string propertyAttribute = "")
{
if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
propertyAttribute += "\n\t";
if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
classAttribute += "\n";

string[] lines = File.ReadAllLines(filePath);
string[] columnNames = lines.First().Split(',').Select(str => str.Trim()).ToArray();
string[] data = lines.Skip(1).ToArray();

string className = Path.GetFileNameWithoutExtension(filePath);
// use StringBuilder for better performance
string code = String.Format("{0}public class {1} {{ \n", classAttribute, className);

for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
{
var columnName = Regex.Replace(columnNames[columnIndex], @"[\s\.]", string.Empty, RegexOptions.IgnoreCase);
if (string.IsNullOrEmpty(columnName))
columnName = "Column" + (columnIndex + 1);
code += "\t" + GetVariableDeclaration(data, columnIndex, columnName, propertyAttribute) + "\n\n";
}

code += "}\n";
return code;
}

public static string GetVariableDeclaration(string[] data, int columnIndex, string columnName, string attribute = null)
{
string[] columnValues = data.Select(line => line.Split(',')[columnIndex].Trim()).ToArray();
string typeAsString;

if (AllDateTimeValues(columnValues))
{
typeAsString = "DateTime";
}
else if (AllIntValues(columnValues))
{
typeAsString = "int";
}
else if (AllDoubleValues(columnValues))
{
typeAsString = "double";
}
else
{
typeAsString = "string";
}

string declaration = String.Format("{0}public {1} {2} {{ get; set; }}", attribute, typeAsString, columnName);
return declaration;
}

public static bool AllDoubleValues(string[] values)
{
double d;
return values.All(val => double.TryParse(val, out d));
}

public static bool AllIntValues(string[] values)
{
int d;
return values.All(val => int.TryParse(val, out d));
}

public static bool AllDateTimeValues(string[] values)
{
DateTime d;
return values.All(val => DateTime.TryParse(val, out d));
}

// add other types if you need...
}

使用示例:

class Program
{
static void Main(string[] args)
{
var cSharpClass = CsvToClass.CSharpClassCodeFromCsvFile(@"YourFilePath.csv", ",", "[DelimitedRecord(\",\")]", "[FieldOptional()]");
File.WriteAllText(@"OutPutPath.cs", cSharpClass);
}
}

有完整代码和工作示例的链接 https://github.com/povilaspanavas/CsvToCSharpClass

关于c# - 从 csv 文件结构生成 c# 模型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com