【问题标题】:How to know child type in the linq如何知道 linq 中的子类型
【发布时间】:2012-08-01 05:27:21
【问题描述】:

我有一个实体用户(基类)。它有三个子实体 Admin 、Manager 和 Member

通过选择所有用户,我如何知道特定用户是管理员、经理或成员。我必须在网格中显示所有用户数据,并将名称列作为我需要显示管理员或经理或成员的类型

【问题讨论】:

  • 为什么不把它作为角色保存在数据库中,然后在课堂上看到。
  • ...您可以通过它进行过滤。会员可以成为经理吗?这将是避免继承的另一个原因。

标签: .net linq entity-framework ef-code-first


【解决方案1】:

这里有一个完整的解决方案。 为每个实例简单调用 GetType() 方法

输出是

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 { }
}

【讨论】:

    【解决方案2】:

    您可以使用Enumerable.OfType Method 来提取某个确切类别的项目的子集合,比如说

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

    或者您可以使用is 运算符来检查每个项目:

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

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2014-09-19
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2010-12-24
      相关资源
      最近更新 更多