54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
namespace ConsoleApp2.Entities;
|
|
|
|
public class DataRecord
|
|
{
|
|
public static bool TryGetField(DataRecord record, string columnName, out string value)
|
|
{
|
|
value = string.Empty;
|
|
if (record.Headers is null)
|
|
throw new InvalidOperationException("Cannot get field when headers of a record have not been set.");
|
|
var idx = Array.IndexOf(record.Headers, columnName);
|
|
if (idx == -1)
|
|
return false;
|
|
value = record.Fields[idx];
|
|
return true;
|
|
}
|
|
|
|
public static string GetField(DataRecord record, string columnName)
|
|
{
|
|
if (record.Headers is null)
|
|
throw new InvalidOperationException("Headers have not been set.");
|
|
var idx = Array.IndexOf(record.Headers, columnName);
|
|
if (idx is -1)
|
|
throw new IndexOutOfRangeException("Column name not found in this record.");
|
|
return record.Fields[idx];
|
|
}
|
|
|
|
|
|
public string[] Fields { get; }
|
|
|
|
public string[]? Headers { get; }
|
|
|
|
public string TableName { get; }
|
|
|
|
|
|
public DataRecord(string[] fields, string tableName, string[]? headers = null)
|
|
{
|
|
if (headers is not null && fields.Length != headers.Length)
|
|
throw new ArgumentException(
|
|
$"The number of fields does not match the number of headers. Expected: {fields.Length} Got: {headers.Length}",
|
|
nameof(fields));
|
|
|
|
Fields = fields;
|
|
TableName = tableName;
|
|
Headers = headers;
|
|
}
|
|
|
|
public string this[int index] => Fields[index];
|
|
|
|
public string this[string columnName] => GetField(this, columnName);
|
|
|
|
public int Count => Fields.Length;
|
|
|
|
public bool TryGetField(string columnName, out string value) => TryGetField(this, columnName, out value);
|
|
} |