Search code examples
c#object-initializers

Assign array value inside object initializer in c#


I have a class as below.

public class PurgeRecord
{
    public int Index { get; set; }
    public string Source { get; set; }
    public int PurgeFileID { get; set; }
    public string AuthorisationID { get; set; }
    public string RecordSystem { get; set; }
    public string KeyName { get; set; }
    public string[] KeyValues { get; set; }
    public bool IsValid { get; set; }
    public string Action { get; set; }
    public string ErrorDetail { get; set; }
    public string FileName { get; set; }
}

I am getting some string values separated by '|' into string array and lopping over it as follows.

string[] test = Convert.ToString(values[5]).Split('|');
foreach (string key in test)
{
    purgeRecord = new PurgeRecord()
    {
        KeyValues = key,
        IsValid = true,
        FileName = "XYZ"
    };
    lstPurgeRecords.Add(purgeRecord);
}

But I am getting an error on key as cannot convert string to string[] implicitly. I tried many ways and tried googling as well but no luck.

Please help.


Solution

  • The KeyValues property type is string array, when you are trying to initialize a PurgeRecord instance you are trying to insert a string into a string[].

    So this is what you should do:

    //Every object instance in C# have the function 'ToString'.
    string[] test = values[5].ToString().Split('|');
    
    foreach (string key in test)
    {
        purgeRecord = new PurgeRecord()
        {
            //Create an array to insert in the values, but probably this is the KeyName
            KeyValues = new[] { key },
            IsValid = true,
            FileName = "XYZ"
        };
        lstPurgeRecords.Add(purgeRecord);
    }
    

    There is a nice way to do with Linq too:

    lstPurgeRecords = values[ 5 ]
                        .ToString()
                        .Split( '|' )
                        .Select( key => new PurgeRecord 
                        {
                            KeyValues = new[] { key },
                            IsValid = true,
                            FileName = "XYZ"
                        } );