Venom
Venom

Reputation: 1106

How to know child type in the linq

I have a entity User(Base Class).Which have three child entity Admin ,Manager and Member

By selecting all the user how can I know that particular user is admin or manager or member. I have to show all the user data in the grid with a column Name as type where I need to show Admin or Manager or Member

Upvotes: 0

Views: 67

Answers (2)

Marty
Marty

Reputation: 3555

Here's a complete solution to this. Simple call the GetType() method for each instance

And the output is enter image description here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestBaseUserConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var users = new List<User>
                {
                    new User {Name = "User1"},
                    new Manager {Name = "User2"},
                    new Member {Name = "User3"},
                    new Student {Name = "User4"}
                };

            users.Select(p => new { p, UserTpe = p.GetType().Name })
                 .ToList()
                 .ForEach(t => Console.WriteLine("User Name = {0}, User Type = {1}", t.p.Name, t.UserTpe));
            Console.ReadLine();
        }
    }

    public class User
    {
        public string Name { get; set; }
    }

    public class Manager : User { }
    public class Member : User { }
    public class Student : User { }
}

Upvotes: 1

horgh
horgh

Reputation: 18553

You could use Enumerable.OfType Method to extract a subcollection of items of some exact class, say

collection.OfType<Admin>().ToList()

Or you could use is operator to check each item:

foreach(User item in collection)
{
    if(item is Admin)
    {
    }
    else
    ...
}

Upvotes: 0

Related Questions