Search code examples
c#listcastingdefaultifempty

List<DataRow>.DefaultIfEmpty() shows error


I need to get a new DataRow from the List<DataRow> object.

Data object has 5 records / rows.

public List<DataRow> Data { get; set; } = new();

private DataRow GetDataRow(COAClassRecord _Record)
{
    DataRow _DataRow = (DataRow)Data.DefaultIfEmpty();
    _DataRow["Id"] = _Record.ID;
    _DataRow["Code"] = _Record.Code;
    _DataRow["Title"] = _Record.Title;
    return _DataRow;
}

But I got an error on this line:

DataRow _DataRow = (DataRow)Data.DefaultIfEmpty();

enter image description here

System.InvalidCastException: Unable to cast object of type 'DefaultIfEmptyIterator`1[System.Data.DataRow]' to type 'System.Data.DataRow'.

Kindly help me to find out how can I get a new DataRow through List<>.DefaultifEmpty or give be better way.


Solution

  • Make sure there is a default DataRow in case your returning list is empty. With that, you can use FirstOrDefault to get the DataRow from IEnumerable with Type <T>.

    First, create a class in C# like below :

    public class COAClassRecord
    {
        public int ID { get; set; }
        public string Code { get; set; }
        public string Title { get; set; }
    }
    

    Then, Refer it to your program like below :

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    
    public class Program
    {
        public static void Main()
        {
            Sample example = new Sample();
            COAClassRecord record = new COAClassRecord { ID = 1, Code = "ABC", Title = "Sample Title" };
            DataRow row = example.GetDataRow(record);        
            Console.WriteLine($"Id: {row["Id"]}, Code: {row["Code"]}, Title: {row["Title"]}");
        }
    }
    
    public class Sample
    {
        public List<DataRow> Data { get; set; } = new();
    
        public DataRow GetDataRow(COAClassRecord _Record)
        {
            DataRow _DataRow = Data.DefaultIfEmpty(CreateDefaultDataRow()).FirstOrDefault();
            if (_DataRow != null)
            {
                _DataRow["Id"] = _Record.ID;
                _DataRow["Code"] = _Record.Code;
                _DataRow["Title"] = _Record.Title;
            }
            return _DataRow;
        }
    
        private DataRow CreateDefaultDataRow()
        {
            
            DataTable table = new DataTable();
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("Title", typeof(string));
    
            
            return table.NewRow();
        }
    }
    

    Refer the working .netfiddle here