开发者

When to use Expression

开发者 https://www.devze.com 2023-04-12 19:45 出处:网络
I am trying to determine what to use ... I have a requirement to pass an IEnumerable<TSource> to a function that writes the entity members\' values to file. Here is what the IEnumerable looks l

I am trying to determine what to use ...

I have a requirement to pass an IEnumerable<TSource> to a function that writes the entity members' values to file. Here is what the IEnumerable looks like:

var persons = new[] {
    new Person {
        RecordID = 0,
        PersonFName = "Joe",
        PersonMName = "",
        PersonLName = "Smith",
        PersonZip="75227"
    }, 
    new Person {
  开发者_运维问答      RecordID = 1,
        PersonFName = "Mary",
        PersonMName = "Hada",
        PersonLName = "Lamb",
        PersonZip="75217"
    }};

What is the best way to pass the IEnumerable to a function that reads each entity so I can read each field value?

I was thinking that I would use something like:

void WriteData<TSource>(Expression<IEnumerable<Person>> expression)
{
    // do stuff
}

I'm having trouble finding resources that explain how to determine when you should use an Expression versus just passing IEnumerable. And then, how do I create the Expression that reflects persons ?

Ideally, it seems like I would call WriteData like so:

WriteData(persons); 

Am I even headed in the right direction?


I see no reason to use an expression tree there. If you just want to fetch all the properties by reflection, I suggest you do that - expression trees won't really help you do that though.

Note that the choice is rarely between Expression and IEnumerable<T> - it's usually either between an expression tree and a delegate, or between IEnumerable<T> and IQueryable<T>.


I have no idea what you'd do with an expression but this is roughly what I'd do using reflection.

public void WriteData<T>(IEnumerable<T> objects) where T : class
{
  foreach (var obj in objects)
  {
    WriteObjectData(obj);
  }
}

private void WriteObjectData<T>(T obj) where T : class
{
    foreach (var propertyInfo in typeof(T).GetProperties())
    {
        // Use propertyInfo.GetValue to get the value from obj. 
    }
}

You could specify an interface instead of where T:class to limit the methods to just your data objects if you wanted to.

0

精彩评论

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

关注公众号