Linq进入Clause Missing Field

时间:2017-07-14 13:53:53

标签: c# linq

我想在输出中同时获取Citizen的Name_surname,但自动完成不会将item.name_surname带入列表中。为什么会这样?执行" INTO"条款?

TLDR:在制作临时结果时,我无法检索患者姓名。

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

namespace LINQ_INTO_CLAUSE
{

public class Citizen
{
    public int id;
    public string name_surname;
}

public class Illness
{
    public int id;
    public string illnessName;
}
class Program
{
    static void Main(string[] args)
    {
        Citizen[] patients = new[]              { new Citizen {id = 123,    name_surname = "John"       },
                                                  new Citizen {id = 2345,   name_surname = "Derek"      },
                                                  new Citizen {id = 345,    name_surname = "Ahmed"      },
                                                  new Citizen {id = 31345,  name_surname = "Mehmed"     }};

        Illness[] illnesses = new[]             { new Illness { id = 123,   illnessName = "Flu"         },
                                                  new Illness { id = 7726,  illnessName = "Flu"         },
                                                  new Illness { id = 123,   illnessName = "Headache"    },
                                                  new Illness { id = 2345,  illnessName = "Kolera"      },
                                                  new Illness { id = 31345, illnessName = "Kolera"      }};


        var _queryResult = from s in patients
                           join k in illnesses on s.id equals k.id
                           into temporaryResult
                           from c in temporaryResult
                           select c;

        foreach (var item in _queryResult)
        {
            Console.WriteLine(item.id+"-"+item.illnessName);
        }
    }
}
}

2 个答案:

答案 0 :(得分:4)

您可以将其存储为匿名类型,不需要into

var _queryResult = from p in patients
                   join i in illnesses on p.id equals i.id
                   select new { Patient = p, Illness = i};

foreach (var x in _queryResult)
{
    Console.WriteLine(x.Illness.id + "-" + x.Illness.illnessName + " - " + x.Patient.name_surname);
}

如果您想使用into关键字来获取公民的所有疾病,您仍然可以将其存储为匿名类型。但请勿在{{1​​}}之后使用from再次展平群组:

into

答案 1 :(得分:0)

您不需要into...位,然后您可以使用所需的详细信息创建更好的匿名类型:

var _queryResult = from s in patients
                   join k in illnesses on s.id equals k.id
                   select new
                   {
                       Name = s.name_surname, 
                       Id = k.id, 
                       Illness = k.illnessName 
                   };

foreach (var item in _queryResult)
{
    Console.WriteLine(item.Name + "-" + item.Id + "-" + item.Illness);
}