How to set change Linq to excel Null string values?

205 Views Asked by At

I have a model to cast an object list using LINQ to excel.

public class Model{
  public string Name { get; set; }
  public string Date { get; set; }
}

and I am using

var result = excelQueryFactory.Warksheet<Model>(0);

But my excel has Null test in name cells. But they should be empty. So my Name properties filled with Null text. How can I excel these text values while filling the model?

4

There are 4 best solutions below

2
Maksim Simkin On BEST ANSWER

You could add following transformation to your excel factory object:

excelQueryFactory.AddTransformation<Model>(x => x.Date, cellValue => cellValue??string.Empty);
excelQueryFactory.AddTransformation<Model>(x => x.Name, cellValue => cellValue??string.Empty);
0
Nicholas Hunter On

Perhaps this very common pattern will fit your requirements.

public class Model {

    private string _name;

    public string Name { 

        get => _name; 

        set {
            _name = (value == null_value) ? empty_value : value;
        }
    } 
}
0
Cem PEHLIVAN On
public class Model
{
    private string _Name;

    public string Name
    {
        get { return _Name; }
        set
        {
            if (string.IsNullOrWhiteSpace(value) || value.ToLower() == "null")
                _Name = null;
            else
                _Name = value;
        }
    }

    public string Date { get; set; }
}
0
Red_Phoenix On

Have you tried casting null values to string using the SELECT option in LINQ?

var result = excelQueryFactory.Warksheet<Model>(0)
    .Select(x => new Model{
        Name = x.Name ?? string.Empty,
        Date = x.Date
    });