开发者

linq to sql only selecting data from columns in object that are not null

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 开发者_如何学JAVAStringBuilder();
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


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


using (var dc = new DataContext())
{
    var result = dc.Entities.Where(x => c.Column != null).Select(x => x.Column)
                 .Aggregate((x, y) => x + y);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜