C#字典透视Linq

时间:2015-08-20 12:09:45

标签: c# linq dictionary dynamic

我有一个这样的词典:

public class MyModel {
    private int id;
    private String title;
    private String thing;
     public static class thing
     {
     private string field1;
     private string field2;
     etc etc
     }
}

现在我需要一些linq语句或lambda表达式(或其他机制)来返回这样的新对象:

Key | Value
C1  | 1
C2  | 2
C3  | 3

问题是键的值只在运行时才知道,因为我只在运行时知道我的新无名对象有多少属性及其名称。

有人可以建议我如何实现我的目标吗?

2 个答案:

答案 0 :(得分:7)

您可以结合使用ExpandoObjectdynamic

1
2
3

这将产生:

This can help 

<html>
<head>

  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
  <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
  <!-- Load jQuery and the validate plugin -->
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>

  <!-- jQuery Form Validation code -->
  <script>

  // When the browser is ready...
  $(function() {

    // Setup form validation on the #register-form element
    $("#register-form").validate({

        // Specify the validation rules
        rules: {
            firstname: "required",
            lastname: "required",
            email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                minlength: 5
            },
            agree: "required"
        },

        // Specify the validation error messages
        messages: {
            firstname: "Please enter your first name",
            lastname: "Please enter your last name",
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            },
            email: "Please enter a valid email address",
            agree: "Please accept our policy"
        },

        submitHandler: function(form) {
            form.submit();
        }
    });

  });

  </script>
</head>
<body>
  <h1>Register here</h1>

  <!--  The form that will be parsed by jQuery before submit  -->
  <form action="" method="post" id="register-form" novalidate="novalidate">

    <div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
    <div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
    <div class="label">Email</div><input type="text" id="email" name="email" /><br />
    <div class="label">Password</div><input type="password" id="password" name="password" /><br />
    <div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>

  </form>

</body>
</html>

Cheers,

Murali P

你可以用它做一个很好的扩展方法。

答案 1 :(得分:0)

这是不可能的......如果你在编译时不知道它的属性,你就不能使用结果对象,而不会跳过Reflection箍(它会更容易使用字典)。