Home > Mobile >  How to cast the object type in List<t>.Except
How to cast the object type in List<t>.Except

Time:07-23

I made two simple classes for user and users, in class user I only have userID, userName and List<string> userGroup, and in class users I have the member for two user and two properties to compare the userGroup.

        public List<string> DifferenceSetAtoB
        {
            get
            {
                return (List<string>)UserA.UserGroups.Except((List<string>)UserB.UserGroups);
            }
        }

what I'm trying to do is to use the Except method to return the difference set between A and B.

but when I run the code, I will get the error message on the return line saying:

System.InvalidCastException HResult=0x80004002 Message=Unable to cast object of type 'd__811[System.String]' to type 'System.Collections.Generic.List1[System.String]'.

My understanding is that the data type of UserB.UserGroups is List and when I use Except it's a method from Collection so the data type is Collections.General.List. But I don't know how to force the data type to be the same. Isn't List is already from System.Collections.Generic? Can anyone please help?

Full code below:

    public class User
    {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public List<string> UserGroups { get; set; }

        public User()
        {
            this.UserGroups = new List<string>();
        }
    }

    public class UserComparison
    {
        public User UserA { get; set; }
        public User UserB { get; set; }

        public List<string> DifferenceSetAtoB
        {
            get
            {
                return (List<string>)UserA.UserGroups.Except((List<string>)UserB.UserGroups);
            }
        }
        public List<string> DifferenceSetBtoA
        {
            get
            {
                return (List<string>)UserB.UserGroups.Except((List<string>)UserA.UserGroups);
            }
        }

        public UserComparison()
        {
            this.UserA = new User();
            this.UserB = new User();
        }
    }

CodePudding user response:

Except(...) returns IEnumerable<> so the cast is invalid. If you want to return a list, you can use ToList() method:

return UserA.UserGroups.Except(UserB.UserGroups).ToList();

As it might take some time to process, it should not be a property. Though it is just a matter of design choice.

  • Related