1

I have a simple LINQ query here:

var Staffs = new[] 
{
    new { id = 1, name = "Jefferson", age = 42},
    new { id = 2, name = "Jacobson", age = 54},
    new { id = 3, name = "Zhang", age = 34}
};

var payroll = new[]
{
    new { pid = 1, wage = 5000},
    new { pid = 2, wage = 6500},
    new { pid = 3, wage = 6700}
};

var q = from stf in Staffs
        from pay in payroll
        where stf.id == pay.pid
        select new
        {
            stfObj = stf,
            pay.pid,
            pay.wage
        };

Here, stfObj would be an object containing the id, name and age fields

Here comes the question:

Is it possible to turn the object into the fields themselves without explicitly hard-coding the field names like this:

select new
{
    stf.id,
    stf.name,
    stf.age,
    pay.pid,
    pay.wage
 };

In this way, there will be no need to change the select new block when I add a new field to Staffs, like Gender for example

Is that possible?

(ok, this looks like the question here... anyway, hoping to get better answers here)

Community
  • 1
  • 1
im_chc
  • 1,023
  • 15
  • 24
  • possible duplicate of [How to select all fields plus some new fields in LINQ?](http://stackoverflow.com/questions/10036421/how-to-select-all-fields-plus-some-new-fields-in-linq) – Daniel Hilgarth Aug 30 '12 at 12:10
  • 2
    How do you plan to access your unnamed fields afterwards ? – Julien Ch. Aug 30 '12 at 12:15

3 Answers3

0

Is this what you want!

select new
{
sId=stfObj.id,
sName=stfObj.name,
sAge=stdObj.age,
pId=pay.pid,
pWage=pay.wage
};
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Why not simply embed your object ?

select new {
    staff = stf,
    pay = pay
};
Julien Ch.
  • 1,231
  • 9
  • 16
0

I do not know, what you need this for. But you could try to use Dictionary<> for this. Say, we have a class:

public class Test
{
    public string Name { get; set; }
    public string Desc { get; set; }    
}

So you can do the following:

List<Test> list = new List<Test>
{
     new Test
     {
         Name = "Test 1",
         Desc = "Desc 1"
     }
};
var temp = list.Select(t =>
                {
                    Dictionary<string, object> values = new Dictionary<string, object>();
                    foreach (PropertyInfo pi in t.GetType().GetProperties())
                        values[pi.Name] = pi.GetValue(t, null);
                    return values;
                })
               .FirstOrDefault();
temp.ToList().ForEach(p => Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value)));

So if you add a property to the Test class, say, like this:

public bool Extra { get; set; }    

You'll get it in the dictionary automatically. Probably you'll have to work with reflection methods overloads to get exactly what you need...

horgh
  • 17,918
  • 22
  • 68
  • 123