代码之家  ›  专栏  ›  技术社区  ›  user32415

如何执行动态linq2sql查询?

  •  2
  • user32415  · 技术社区  · 16 年前

    我正在尝试构建一个方法,该方法将接收一个linq表,并应返回一个值列表,该列表将是一个dropdownlist数据源。

    这就是我现在所拥有的:

    public static List<Structs.NameValuePair> GenDropDownItens<T>(string ValueField , string TextField ) where T: class
    

    我不知道该怎么做,查询表,只获取传递的字段(valuefield,textfield)…。

    TKS!

    5 回复  |  直到 16 年前
        1
  •  3
  •   user7116    16 年前

    将linq2sql查询的结果投影到system.collections.generic.keyvaluepair对象中,如下所示:

    
    ddl.DataSource = DataContext.Table.Select(o => new KeyValuePair<string, string>(o.ID, o.DisplayField));
    ddl.DataBind();
    

    然后,您需要将dropdownlist上的datavaluefield和datatextfield属性分别设置为“key”和“value”。

        2
  •  1
  •   Nick Berardi    16 年前

    为什么不做一些像这样的事情;

    var dropDownValues = dataContext.SomeTable.ToDictionary(
        s => s.Name,
        s => s.Value
    );
    
    foreach(var item in dropDownValues) {
        var OptionName = item.Key;
        var OptionValue = item.Value
    };
    

    希望这有帮助,我真的不认为你需要创造一段时间的方法。但是如果你想的话,我会说让它取一个idictionary对象,然后从那里转换它。

        3
  •  0
  •   Daniel M    16 年前

    表.选择(t=>t.field1,t.field2)

    也可以看看斯科特·古瑟里的博客系列 here 是的。

        4
  •  0
  •   cosullivan    16 年前

    你想用你的方法做如下的事情吗

    getDropDownitems(“gates”,“lastname”)???是吗?

    如果是这样,sdk示例中包含一个名为dynamicquery的项目。使用此功能,基本上可以创建所需查询的文本版本。你可以这样做

    “姓氏=='盖茨'”

    然而,自己构建表达式树也同样容易。了解表达式树外观的最佳方法是使用ExpressionTreeVisualizer vs Debugger外接程序(注意,这也是sdkcsharpSamples中包含的另一个示例)。就像是

    parameterExpression parameter=表达式.参数(typeof(t),“x”); var expression=expression.equals(expression.property(parameter,“lastname”),expression.constant(“gates”)

        5
  •  0
  •   Timothy Khouri    16 年前

    如果“key”和“value”是表示要获取的属性名称的字符串,并且它们只在运行时才知道…这是你的密码:

    private static Func<T, DictionaryEntry> GetNameValuePairFunc<T>(string valueField, string textField)
    {
        Func<T, DictionaryEntry> result = (item) =>
        {
            object key = typeof(T).GetProperty(valueField).GetValue(item, null);
    
            object text = typeof(T).GetProperty(textField).GetValue(item, null);
    
            return new DictionaryEntry(key, text);
        };
    
        return result;
    }