gpt4 book ai didi

c# - 如何使用 C# 读取此文本文件并将其存储在列表中

转载 作者:行者123 更新时间:2023-11-30 22:59:37 24 4
gpt4 key购买 nike

文本文件数据如下:

S.No    Name        Description Quantity    Rate    Discount    Amount1       Apple       Friut is    12      24.02       0           242                    Good for                    health2       Orange      Friut       5       12.22       3           1283       Banana      Friut       5       12.22       3           1284       Grapes      Friut       5       12.22       3           128

I want to add all the Rows& Columns in list but Description column have multiple Rows in single item. How can I Solve this. I add My Existing Code Here:

My Existing Code is as follows:

class Program
{
static void Main(string[] args)
{
var dd = File.ReadAllLines(
"C:\\Users\\Trainee\\Desktop\\Saravanan_Test\\27.8.2018\\Inputfile.txt")
.Skip(1)
.Where(s => s.Length > 1)
.Select(x => splits(x)).ToList();

foreach (var item in dd)
{
Console.WriteLine(item.id+"\t"
+ item.Name+"\t"
+ item.Description+"\t"
+ item.Quantity+"\t"
+ item.Rate+"\t"
+ item.Discount+"\t"
+ item.Amount);
}

Console.ReadKey();

}

private static Class1 splits(string x)
{
var columns = x.Split('\t').Where(c => c != "").ToList();
return new Class1
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
};
}
}

class Class1
{
public int id { get; set; }
public string Name { get; set; }
public String Description { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public int Discount { get; set; }
public int Amount { get; set; }
}

我想像这样将数据存储到列表中:

list.Add(new{ sno=1, Name="Apple", 
Description="Friut is good for Health",
Quantity=12, Rate=24.02, Discount=0,
Amount=242 });

提前致谢。

最佳答案

注意:此解决方案基于有问题的共享文件。数据以空格分隔,格式不宜使用。回答以帮助他拥有的内容格式的人。已经过测试和工作。

static void Main(string[] args)
{
List<Data> list = new List<Data>();

var dd = File.ReadAllLines(@"C:\Users\XXXX\Desktop\test.txt")
.Skip(1)
.Where(s => s.Length > 1).ToList();

foreach (var item in dd)
{
var columns = item.Split('\t').Where(c => c.Trim() != string.Empty).ToList();

if (columns != null && columns.Count > 0)
{
int id;

if (int.TryParse(columns[0], out id))
{
list.Add(new Data()
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
});
}
else
{
list.Last().Description += columns[0];
}
}
}

Console.ReadLine();
}

关于c# - 如何使用 C# 读取此文本文件并将其存储在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089854/

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