Dan
Dan

Reputation: 45752

How to make an anonymous type property nullable in the select of a linq to sql query

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?

Upvotes: 1

Views: 2267

Answers (3)

Sivaprasath
Sivaprasath

Reputation: 400

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.:-)

Upvotes: 2

Martin Mulder
Martin Mulder

Reputation: 12954

Try:

select new
{
    O.A,
    B = (int?)0
}

Upvotes: 2

usr
usr

Reputation: 171178

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.

Upvotes: 1

Related Questions