views:

27

answers:

2

hi there

i am trying to build up a string containing the values of fields in a linq to sql object. the thing is, i only want to grab the fields that are not null

i am sure there is a way to do this. can anyone enlighten me?

mylinqdatacontext dc = new mylinqdatacontext;
StringBuilder sb = new StringBuilder();
mylinqtype item = (from x in dc.mylinqtypes where x.id.equals(1)).single();
var props = typeof(mylinqtype).GetProperties();

foreach(PropertyInfo p in props){

  if(item... != null){
    sb.append(p.name + " :" + item[p].value; //or some such i dont really know
  }
}

any help much appreciated

i have tried

object theValue =  p.getgetmethod().invoke(item, null); 

but it threw a System.Reflection.TargetException thanks

nat

A: 
using (var dc = new DataContext())
{
    var result = dc.Entities.Where(x => c.Column != null).Select(x => x.Column)
                 .Aggregate((x, y) => x + y);
}
Koistya Navin
The poster wants to create a string representation of an entity, but only the non-null properties will be included. I'm not sure where you're going with your query.
Marc
+1  A: 

This is untested, but I think it should get you close at least:

SomeDataContext dc = new SomeDataContext();
StringBuilder sb = new StringBuilder();

SomeItem item = (from x in dc.SomeItems where x.SomeItemId == 1 select x).Single();
PropertyInfo[] props = item.GetType().GetProperties();

foreach (PropertyInfo p in props)
{
    if (p.CanRead) // might need more tests here for various attributes of the property
    {
        object val = p.GetValue(item, null);

        if (val != null)
        {
            sb.Append(p.Name + " : " + val);
        }
    }
}
Smashd
thanks, worked fineactually i think my initial version would probably have worked too, but i was realised i hadnt dont the .first()/.single()doh!
nat