开发者

Possible to assign a data type to an anonymous type's members in a linq query?

开发者 https://www.devze.com 2022-12-29 13:42 出处:网络
If I have a linq query that creates the anonymous type below: select new { lf.id, lf.name, lf.desc, plf.childId

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 ty开发者_JAVA百科pe to one of the members? Specifically I would like to make lf.id a null-able int rather than an int...


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

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

To force the cast?

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 that worked fine.


That may not work. In anonymous types, the data type of the property is used. So in the new type, the data type of id would be used to create a property id in the new type.

If the id property in 'lf' is nullable, then you should be able to have it nullable in the anonymous type as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号