Need to cast explicitly thru anonymous type in Union()

后端 未结 2 1523
我在风中等你
我在风中等你 2021-01-20 01:11

I have 2 var/objects, retrieving thru these 2 functions:

private IQueryable SelectAll_1(...)
{
    return query;
}

class Pro

2条回答
  •  情歌与酒
    2021-01-20 01:12

    You can't union two different types, unless one inherits from the other (for example, you could potentially find a union of IEnumerable and IEnumerable, although that would rarely be useful).

    Now in your case, it sounds like Project and Project_test should really be one type, if the various properties have the same meaning. Currently the ID properties have different types - but is that really necessary or desirable? If they're both identifiers with the same scope, it makes sense to store them in the same representation. If the properties don't have the same meaning, you shouldn't be forming a union between them at all. If they do have the same meaning, you should try to make both sequences use the same type.

    You could use anonymous types for this, in this way:

    var projectedP1 = P1.Select(x => new { x.ID, x.col1, x.col2, x.col3 });
    var projectedP2 = P2.Select(x => new { ID = int.Parse(x.ID_inString),
                                                x.col1, x.col2, x.col3 });
    var union = projectedP1.Union(projectedP2);
    

    Or you could just use one of the existing types:

    var projectedP1 = P1.Select(x => new Project_test { 
                                         ID_inString = x.ID.ToString(), 
                                         col1 = x.col1, 
                                         col2 = x.col2, 
                                         col3 = x.col3 });
    var union = projectedP1.Union(P2);
    

    It's not really obvious which of these is a better idea - but I'd go back to trying to reconcile the two types if possible, at which point you have no problems anyway.

    提交回复
    热议问题