使用linq为列表中的字段赋值

时间:2016-08-26 05:00:49

标签: c# linq

我有两个班级工人和公司,比如说

class worker {
string name;
string company_id;
string company_name;
}

class Company{
string c_name;
string c_id;
}

现在,我想要一个linq,这样当company_id和c_id匹配时,将company_name分配给c_name。最初,company_name为null。我想用linq填写值。

2 个答案:

答案 0 :(得分:0)

假设您有workerscompanies的列表,并且可以遍历它们:

foreach (worker w in workers)
{
    if (companies.Any(c => c.c_id == w.company_id))
        w.company_name = companies.Where(c => c.c_id == w.company_id).Select(comp => comp.c_name).Single();
}

答案 1 :(得分:0)

这是你在找什么?

public class Worker 
{
    public string Name {get;set;}
    public string CompanyId {get;set;}
    public string CompanyName {get;set;}
}

public class Company
{
 public string Name {get;set;}
 public string Id {get;set;}
}


   var companyList = new List<Company>
    {
        new Company{Id = "1", Name = "Company 1"},
        new Company{Id = "2", Name = "Company 2"},
        new Company{Id = "3", Name = "Company 3"}
    };

    var workerList = new List<Worker>
    {
        new Worker{ Name = "Worker 1", CompanyId = "2" },
        new Worker{ Name = "Worker 2", CompanyId = "1" },
        new Worker{ Name = "Worker 3", CompanyId = "2" },
        new Worker{ Name = "Worker 4", CompanyId = "3" },
        new Worker{ Name = "Worker 5", CompanyId = "1" }
    };

workerList.ForEach(w => {
            w.CompanyName = companyList.FirstOrDefault(c=>c.Id == w.CompanyId)?.Name;
        });


foreach(var w in workerList)
{
    Console.WriteLine(w.Name+"-"+w.CompanyName);
    // ==> output will be
    //Worker 1-Company 2
    //Worker 2-Company 1
    //Worker 3-Company 2
    //Worker 4-Company 3
    //Worker 5-Company 1
}

或者如果想要了解加入Linq,那么

var workers =   (from worker in workerList
                join company in companyList
                on worker.CompanyId equals company.Id
                select new Worker 
                 {
                    Name = worker.Name,
                    CompanyId = worker.CompanyId,
                    CompanyName = company.Name
                 }).ToList();