如何使用linq加入员工和性别列表

时间:2018-08-28 08:34:02

标签: c# linq

我已检索员工列表。我的员工类别列(employeeId,姓氏,genderid)

 List<m_employees> Items = new List<m_employees>
                    {
                        new m_employees{ employeeid = 1, lastname = "mike", genderid = 1 },
                        new m_employees{ employeeid = 2, lastname = "jeni", genderid = 2 }
                    };

然后我有我的性别类别列(id,标题)

    List<m_genders> genders = new List<m_genders>
                {
                    new m_genders{ id = 1, title = "Male" },
                    new m_genders{ id = 2, title = "Female" }
                };

//then i tried joining the retrieved list of employees to the genders

var x = from emp in Items
                    join sex in genders
                    on emp.genderid equals sex.id
                    into a from b in a.DefaultIfEmpty(new m_genders())
                    select new
                    {
                        emp.lastname,
                        emp.genderid,
                        sex = b.title
                    };

红色错误行显示给关键字join,并说“ join子句中的表达式之一的类型不正确...”

我如何才能正确加入他们?

2 个答案:

答案 0 :(得分:1)

之所以会这样,是因为emp.genderid,sex.id类型不同,您需要像这样显式地转换或转换它们:

(int)emp.genderid equals sex.id

我能够使用以下类定义来重现错误:

class m_genders
{
    public int id { get; set; }
    public string title { get; set; }

}

class employee
{
   public int id;
   public uint genderid;
   public string lastname { get; set; }
}

答案 1 :(得分:0)

您的问题不清楚,代码可以正常工作:

namespace WindowsFormsApp1
{
    public class m_genders
    {
        public int id;
        public string title;
    }

    public class m_employees
    {
        public int employeeid { get; set; }
        public int genderid { get; set; }
        public string lastname { get; set; }

    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<m_genders> genders = new List<m_genders>
            {
                new m_genders {id = 1, title = "Male"},
                new m_genders {id = 2, title = "Female"}
            };

            List<m_employees> Items = new List<m_employees>
            {
                new m_employees{ employeeid = 1, lastname = "mike", genderid = 1 },
                new m_employees{ employeeid = 2, lastname = "jeni", genderid = 2 }
            };


            var x = from emp in Items
                join sex in genders
                    on emp.genderid equals sex.id
                    into a
                from b in a.DefaultIfEmpty(new m_genders())
                select new
                {
                    emp.lastname,
                    emp.genderid,
                    sex = b.title
                };
        }
    }
}