Fachrul Rozi
Fachrul Rozi

Reputation: 1

Select multiple column in linq

I am very stuck and hope your help.

How to write

select table1.*, table2.column1 as name

in linq?

I tried:

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

but it's output is splitted, eg:

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

I want the output like:

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

thanks.

Upvotes: 0

Views: 278

Answers (1)

Akshay Kumar
Akshay Kumar

Reputation: 21

I think solution will be like this,

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

UPDATE

JsonConvert.SerializeObject() Serialize the newly created object using linq into json and resolve the issue your are facing. I hope you like my answer Thanks

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

Upvotes: 1

Related Questions