1

Consider this simplified example query:

dt = (
  from O in ...
  ...
   select new
   {
      O.A,
      B = 0
   }).ToList().ToDataTable()

Where .ToDataTable() comes from Convert generic List/Enumerable to DataTable?

Assuming that table O does not have an attribute called B but I want to have a column called B whose values I will fill in later. This works fine when B get number values sent to it but i actually want to send it int? values and at present it crashes if it gets send a null.

Is there a way to select a new column (e.g. B) such that it is a nullable type?

Community
  • 1
  • 1
Dan
  • 45,079
  • 17
  • 88
  • 157

3 Answers3

2

Try:

select new
{
    O.A,
    B = (int?)0
}
Martin Mulder
  • 12,642
  • 3
  • 25
  • 54
2

You can do like this,

var testNull = (from student in studentList
                select new
                {
                    RollNo = default(int?),
                    Name = student.Name
                }).ToList();

But better we can create concrete type instead of depending upon a anonymous type based on value.:-)

Sivaprasath
  • 400
  • 1
  • 7
1

Since the type of anonymous type members is inferred make it infer the right thing: B = (int?)null.

Not sure what you mean by "fill in later". If you want B to be mutable you need to create a class.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Apologies, by "fill it in later" I mean I convert `q` to a DataTable and then manually assign values into column `B` of the `DataTable` – Dan May 14 '15 at 11:22