barteloma
barteloma

Reputation: 6875

How to set change Linq to excel Null string values?

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?

Upvotes: 1

Views: 223

Answers (4)

Maksim Simkin
Maksim Simkin

Reputation: 9679

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);

Upvotes: 0

Red_Phoenix
Red_Phoenix

Reputation: 507

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
    });

Upvotes: 0

Cem PEHLIVAN
Cem PEHLIVAN

Reputation: 139

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; }
}

Upvotes: 1

Nicholas Hunter
Nicholas Hunter

Reputation: 1845

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;
        }
    } 
}

Upvotes: 1

Related Questions