Search code examples
c#windowsparsingfilehelpers

FileHelpers: Searching into results


I use the powerful FileHelpers Library. But is there a built-in way to search over the generated objets.

var engine = new FileHelperEngine<Text>();
var res = engine.ReadFile("myfile.csv");
string result = res["key"].value;

My csv is like : key;value
I mean, is it possible not to access objects with the array [0], [1], [12]...
maybe like in the code example.

Thanks a lot !


Solution

  • You can convert your resulting array to a dictionary via LINQ with:

    var dictionary = validRecords.ToDictionary(r => r.Key, r => r.Value);
    

    The following complete program demonstrates the approach.

    [DelimitedRecord(",")]
    public class ImportRecord
    {
        public string Key;
        public string Value;
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var engine = new FileHelperEngine<ImportRecord>();
    
            string fileAsString = @"Key1,Value1" + Environment.NewLine +
                                  @"Key2,Value2" + Environment.NewLine;
    
            ImportRecord[] validRecords = engine.ReadString(fileAsString);
    
            var dictionary = validRecords.ToDictionary(r => r.Key, r => r.Value);
    
            Assert.AreEqual(dictionary["Key1"], "Value1");
            Assert.AreEqual(dictionary["Key2"], "Value2");
    
            Console.ReadKey();
        }
    }