使用C#實(shí)現(xiàn)將CSV文件內(nèi)容裝配成對(duì)象列表
寫(xiě)在前面
CSV文件采用純文本的存儲(chǔ)形式,字段間以分隔符進(jìn)行區(qū)分,行之間以換行符進(jìn)行切換,既可以用文本編輯器打開(kāi)也可以用Excel編輯,可讀性非常好,在游戲開(kāi)發(fā)領(lǐng)域經(jīng)常將其作為數(shù)值配置文件使用。文本編輯器推薦EmEditor,輕巧而不失強(qiáng)大,策劃們用的愛(ài)不釋手。程序?qū)⑴渲梅葱蛄谢?,裝箱成對(duì)象列表,就可以隨意訪問(wèn)和操作了。
代碼實(shí)現(xiàn)過(guò)程可以直接File.ReadAllLine,然后再逐行按分隔符分割,也可以使用專(zhuān)門(mén)的類(lèi)庫(kù)來(lái)操作;本文直接用現(xiàn)成的輪子LumenWorks.Framework.IO類(lèi)庫(kù),通過(guò)NuGet獲取并安裝。

代碼實(shí)現(xiàn)
public static class CsvHelper
{
public static List<T> GetDataList<T>(string csvFilePath) where T : class
{
var list = new List<T>();
if (!File.Exists(csvFilePath))
{
return list;
}
var csvType = typeof(T);
var content = File.ReadAllBytes(csvFilePath);
using (var ms = new MemoryStream(content))
using (var sr = new StreamReader(ms, Encoding.GetEncoding("UTF-8"), true))
using (var tr = sr as TextReader)
{
var cr = new CsvReader(tr, true);
var props = csvType.GetProperties();
var heads = cr.GetFieldHeaders();
while (cr.ReadNextRecord())
{
try
{
object obj = Activator.CreateInstance(csvType);
foreach (var prop in props)
{
if (!heads.Contains(prop.Name))
continue;
string value = cr[prop.Name];
prop.SetValue(obj, GetDefaultValue(prop, value), null);
}
list.Add(obj as T);
}
catch (Exception ex)
{
// log here
continue;
}
}
}
return list;
}
private static object GetDefaultValue(PropertyInfo prop, string value)
{
switch (prop.PropertyType.Name)
{
case "String":
return value.ToNormalString();
case "Int32":
return value.ToInt32();
case "Decimal":
return value.ToDecimal();
case "Single":
return value.ToFloat();
case "Boolean":
return value.ToBoolean();
case "DateTime":
return value.ToDateTime();
case "Double":
return value.ToDouble();
default:
return null;
}
}
#region 類(lèi)型轉(zhuǎn)換方法
/// <summary>
/// 對(duì)象類(lèi)型轉(zhuǎn)換為Int32
/// </summary>
public static int ToInt32(this object obj)
{
if (obj == null)
return 0;
try
{
Type type = obj.GetType();
if (type == typeof(double) ||
type == typeof(float) ||
type == typeof(decimal))
return (int)obj;
int tmp;
if (int.TryParse(obj.ToString(), out tmp))
return tmp;
}
catch
{
return 0;
}
return 0;
}
/// <summary>
/// String to int.
/// </summary>
public static int ToInt32(this string obj)
{
if (string.IsNullOrEmpty(obj))
return 0;
try
{
if (obj.Contains("."))
return (int)Convert.ToSingle(obj);
int tmp;
if (int.TryParse(obj, out tmp))
return tmp;
}
catch
{
return 0;
}
return 0;
}
/// <summary>
/// Double To Int
/// </summary>
public static int ToInt32(this double value)
{
try
{
return (int)value;
}
catch
{
return 0;
}
}
/// <summary>
/// Float To Int
/// </summary>
public static int ToInt32(this float value)
{
try
{
return (int)value;
}
catch
{
return 0;
}
}
/// <summary>
/// 對(duì)象類(lèi)型轉(zhuǎn)換為Int32
/// </summary>
public static long ToInt64(this object obj)
{
if (obj == null)
return 0;
try
{
long tmp;
if (long.TryParse(obj.ToString(), out tmp))
return tmp;
}
catch
{
return 0;
}
return 0;
}
/// <summary>
/// 轉(zhuǎn)換為字符串
/// </summary>
public static string ToNormalString(this object obj)
{
if (obj == null)
return string.Empty;
try
{
return Convert.ToString(obj);
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 轉(zhuǎn)換為日期
/// </summary>
public static DateTime ToDateTime(this object obj)
{
if (obj == null)
{
return Convert.ToDateTime("1970-01-01 00:00:00");
}
try
{
return Convert.ToDateTime(obj.ToString());
}
catch
{
return Convert.ToDateTime("1970-01-01 00:00:00");
}
}
/// <summary>
/// 轉(zhuǎn)換為布爾型
/// </summary>
public static bool ToBoolean(this object obj)
{
if (obj != null)
{
string type = obj.GetType().Name;
switch (type)
{
case "String":
return (obj.ToString().ToLower() == "true" || obj.ToString() == "1");
case "Int32":
return ((int)obj) == 1;
case "Boolean":
return (bool)obj;
default:
return false;
}
}
return false;
}
/// <summary>
/// 轉(zhuǎn)換為十進(jìn)制數(shù)值
/// </summary>
public static Decimal ToDecimal(this object obj)
{
decimal result = 0M;
if (obj == null)
{
return 0M;
}
switch (obj.GetType().Name)
{
case "Int32":
return decimal.Parse(obj.ToString());
case "Int64":
return decimal.Parse(obj.ToString());
case "Boolean":
if ((bool)obj)
{
return 1M;
}
return 0M;
}
var resultString = Regex.Replace(obj.ToString(), "[^0-9.]", "");
result = resultString.Length == 0 ? 0M : decimal.Parse(resultString);
if (obj.ToString().StartsWith("-"))
{
result *= -1M;
}
return result;
}
/// <summary>
/// 轉(zhuǎn)換為雙精度.
/// </summary>
public static double ToDouble(this object obj)
{
double d;
if (double.TryParse(Convert.ToString(obj), out d))
return d;
else
return 0;
}
/// <summary>
/// 轉(zhuǎn)換為單精度.
/// </summary>
public static float ToFloat(this object value)
{
var v = value.ToNormalString();
if (v == "")
{
return 0;
}
else
{
float result;
if (float.TryParse(v, out result))
{
return result;
}
else
{
return 0;
}
}
}
/// <summary>
/// 時(shí)間轉(zhuǎn)換.
/// </summary>
public static DateTime ToDateTimeOrCurrent(this object obj)
{
DateTime dt;
if (DateTime.TryParse(Convert.ToString(obj), out dt))
return dt;
else
return DateTime.Now;
}
#endregion
}示例 CSV 文件內(nèi)容:
Name,Age,IsMale,Birthday
Lee,28,TRUE,1996/1/1
Jane,29,FALSE,1997/11/1
示例 CSV 文件對(duì)應(yīng)的反序列化目標(biāo)類(lèi):
public class TestConfig
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsMale { get; set; }
public DateTime Birthday { get; set; }
}調(diào)用示例
var csvFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestConfigs.csv");
var list = CsvHelper.GetDataList<TestConfig>(csvFilePath);
foreach (var item in list)
{
var name = item.Name;
var age = item.Age;
var isMale = item.IsMale;
var birthday = item.Birthday;
var sex = isMale ? "male" : "female";
Console.WriteLine($"{name} is {sex}");
}執(zhí)行結(jié)果:

以上就是使用C#實(shí)現(xiàn)將CSV文件內(nèi)容裝配成對(duì)象列表的詳細(xì)內(nèi)容,更多關(guān)于C# CSV裝配成對(duì)象列表的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#泛型集合類(lèi)型實(shí)現(xiàn)添加和遍歷
這篇文章介紹了C#泛型集合類(lèi)型實(shí)現(xiàn)添加和遍歷的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
C#中DataTable的創(chuàng)建與遍歷實(shí)現(xiàn)
這篇文章主要介紹了C#中DataTable的創(chuàng)建與遍歷實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
c#不使用系統(tǒng)api實(shí)現(xiàn)可以指定區(qū)域屏幕截屏功能
這篇文章主要介紹了不使用系統(tǒng)API通過(guò)純c#實(shí)現(xiàn)屏幕指定區(qū)域截屏功能,截屏后還可以保存圖象文件,大家參考使用吧2014-01-01
解析如何正確使用SqlConnection的實(shí)現(xiàn)方法
本篇文章對(duì)如何正確使用SqlConnection的實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#生成指定范圍內(nèi)的不重復(fù)隨機(jī)數(shù)
對(duì)于隨機(jī)數(shù),大家都知道,計(jì)算機(jī)不 可能產(chǎn)生完全隨機(jī)的數(shù)字,所謂的隨機(jī)數(shù)發(fā)生器都是通過(guò)一定的算法對(duì)事先選定的隨機(jī)種子做復(fù)雜的運(yùn)算,用產(chǎn)生的結(jié)果來(lái)近似的模擬完全隨機(jī)數(shù),這種隨機(jī)數(shù)被稱(chēng) 作偽隨機(jī)數(shù)。偽隨機(jī)數(shù)是以相同的概率從一組有限的數(shù)字中選取的。2015-05-05
C# 多線(xiàn)程處理List數(shù)據(jù)的示例代碼
這篇文章主要介紹了C# 多線(xiàn)程處理List數(shù)據(jù)的示例代碼,幫助大家更好的理解和使用c#編程語(yǔ)言,感興趣的朋友可以了解下2020-12-12
C#中parallel.foreach實(shí)現(xiàn)多線(xiàn)程處理
Parallel.ForEach方法是C#中的一個(gè)并行循環(huán)方法,它可以并行地對(duì)一個(gè)集合進(jìn)行迭代操作,本文主要介紹了C#中parallel.foreach實(shí)現(xiàn)多線(xiàn)程處理,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
C#使用OpenCvSharp4庫(kù)讀取電腦攝像頭數(shù)據(jù)并實(shí)時(shí)顯示
OpenCvSharp4庫(kù)是一個(gè)基于.Net封裝的OpenCV庫(kù),本文主要給大家介紹了C#使用OpenCvSharp4庫(kù)讀取電腦攝像頭數(shù)據(jù)并實(shí)時(shí)顯示的詳細(xì)方法,感興趣的朋友可以參考下2024-01-01
C#利用TreeView控件實(shí)現(xiàn)目錄跳轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了C#潤(rùn)滑利用TreeView控件實(shí)現(xiàn)目錄跳轉(zhuǎn)功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動(dòng)手嘗試一下2022-07-07

