I want to read a single Value from a CSV File (e.g. Line 3, Column 2).
I'm using the LINQtoCSV NuGet Paket (https://www.codeproject.com/Articles/25133/LINQ-to-CSV-library#_articleTop)
class Product
{
[CsvColumn(Name = "Steckplatz", FieldIndex = 1)]
public String Name { get; set; }
[CsvColumn(CharLength = 5, FieldIndex = 2)]
public short Steckzyklen { get; set; }
[CsvColumn(OutputFormat = "yyyy-MM-dd HH:mm:ss", FieldIndex = 3)]
public DateTime Austauschdatum { get; set; }
}
static void Main(string[] args)
{
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
CsvContext cc = new CsvContext();
IEnumerable<Product> products =
cc.Read<Product>("Insert Steckzyklen Zähler.csv", inputFileDescription);
var productsByName =
from p in products
orderby p.Name
select new { p.Name, p.Steckzyklen, p.Austauschdatum };
Console.WriteLine(products);
}
The variable "products" is an IEnumerable. The whole CSV File gets saved in products.
This is my CSV File:
Steckplatz,Steckzyklen,Austauschdatum
KnaufUpdateBox1Steckplatz1,159,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz2,256,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz3,15896,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz4,489,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz5,6875,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz6,2856,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz7,874,2022-02-25 14:30:32
KnaufUpdateBox1Steckplatz8,3874,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz1,3689,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz2,3689,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz3,983,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz4,287,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz5,398,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz6,28567,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz7,389,2022-02-25 14:30:32
KnaufUpdateBox2Steckplatz8,938,2022-02-25 14:30:32
with LINQPad i could view what was stored in products. I have not managed to get only a specific value from products. Could someone help?
Thanks in advance.
CodePudding user response:
(e.g. Line 3, Column 2).
Assuming products is presented in the order of the file
products.Skip(2).First().Steckzyklen;
Skip
skips past the initial two items in the enumeration,First
grabs the third item, andSteckzyklen
gets the second column
The notion of "column 2" is somewhat lost in favor of named properties, such being the whole raison d'etre for LINQtoCSV; you could recover it by programmatically inspecting the attributes for which one has FieldIndex 2, but I figure that this is a nonsense when FieldIndex=2 is hard coded, and Steckzyklen is hard coded; they're thus synonymous