2011-05-11 110 views
1

嘿,我被困在将简单的Linq语句从查询语法转换为流畅的C#语法。我认为这是可能的,但我需要一个提示。将LINQ语句从查询转换为流畅的c#语法

from property in target.GetType().GetProperties() 
select new 
{ 
    Name = property.Name, 
    Value = property.GetValue(target, null) 
}; 

到..

var props = target.GetType().GetProperties().Select(p=>p.Name....) 

我需要Select后更改?

+1

你到底在问什么? – driis 2011-05-11 20:16:44

+0

'....'是我的问题。对不清楚的问题抱歉。我的编辑正确 – Custodio 2011-05-11 20:33:01

回答

11
var props = target 
    .GetType() 
    .GetProperties() 
    .Select(p => new { 
     Name = p.Name, 
     Value = p.GetValue(target, null) 
}); 
+0

完美!谢谢,因为ReSharper建议我改成:'origin.GetType()。GetProperties()。Select(p => new {p.Name,Value = p.GetValue(origin,null)});'Name = p。名字是不必要的。 – Custodio 2011-05-11 20:20:13

+1

在这种情况下确实没有必要,但它也是在其他语法中。 :)我想也许你有一个需要它的编码风格,例如与下面的行保持一致的外观。 – 2011-05-11 20:24:47

1
var props = target.GetType() 
        .GetProperties() 
        .Select(p => new { 
         Name = p.Name, 
         Value = p.GetValue(target, null) 
        });