Is it possible to assign datatype to members of anonymous type in linq query?

If I have a linq query that creates the anonymous type below:

                    select new
                    {
                        lf.id,
                        lf.name,
                        lf.desc,
                        plf.childId
                    };

      

Is it possible to assign a specific type to one of the members? Specifically, I would like to make lf.id a null int, not an int ...

+2


a source to share


2 answers


Not sure if this will work without trying, but you could do this:

select new
{
  (int?)lf.id,
}

      

To force the casting?



Edit: looks like no, but I was able to do this:

List<int> il = new List<int>(){1,2,3};
var z = from i in il.AsQueryable<int>()
select new
{
    Foo = (int?)i
};

      

And it worked fine.

+5


a source


It might not work. Anonymous types use the property data type. Thus, in the new type, the id data type will be used to create the property identifier in the new type.



If the id property in 'lf' is NULL, then you must also have its nullable value in the anonymous type.

0


a source







All Articles