【问题标题】:Select multiple column in linq在linq中选择多列
【发布时间】:2021-12-11 14:23:08
【问题描述】:

我很困,希望你的帮助。

怎么写

select table1.*, table2.column1 as name

在 linq 中?

我试过了:

select new { table1, name = table2.column1 })

但它的输出是分裂的,例如:

table1:{address:valueOfAddress, religion:valueOfReligion, columnN:valueofColumnN}, name: valueOfName

我想要这样的输出:

address:valueOfAddress, religion:valueOfReligion, columnN:valueofColumnN, name: valueOfName

谢谢。

【问题讨论】:

标签: c# linq


【解决方案1】:

我认为解决方案是这样的,

var result = from t1 in table1 
             from t2 in table2
             where condition // if there is any condition to fetch records 
             select new { address = t1.address, religion=  t1.religion,columnN = t1.columnN, Name = t2.name };

更新

JsonConvert.SerializeObject() 使用 linq 将新创建的对象序列化为 json 并解决您面临的问题。 希望你喜欢我的回答 谢谢

class Employee
{
    public string employeeID;
    public string Name;
    public string eventName;
 
    public Employee(string eID, string eName, string eEvents)
    {
        this.employeeID = eID;
        this.Name = eName;
        this.eventName = eEvents;
    }
}

class Event
{
    public int id { get; set; }
    public string name { get; set; }

    public Event(int _id,string _name)
    {
        id = _id;
        name = _name;
    }
}
class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>();
        employees.Add(new Employee("PALI_e1", "Parvez Ali", "FOOTBALL"));
        employees.Add(new Employee("AALI_e2", "Ashik Ali", "FOOTBALL"));
        employees.Add(new Employee("AALI_e3", "Aftab Ali", "CHESS"));
        employees.Add(new Employee("AALI_e4", "Arif Ali", "CRICKET"));

        List<Event> courses = new List<Event>();
        courses.Add(new Event(1,"FOOTBALL"));
        courses.Add(new Event(2,"FOOTBALL"));

        var result = from l1 in employees
                     from l2 in courses
                     where l1.eventName == l2.name
                     select new { l1, l2.name };

        string output = JsonConvert.SerializeObject(result);
        Console.WriteLine(output);
    }
}

Here is expected output screenshot

【讨论】:

  • 我要选择 *,而不是逐列。如果我们的专栏太多,我们很难。
  • 使用 JsonConvert.SerializeObject() 您可以使用 linq 将新创建的对象更改为 json,它将类​​似于您的预期输出,
猜你喜欢
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
相关资源
最近更新 更多