简体   繁体   English

LINQ - 向datacontext添加函数

[英]LINQ - adding function to datacontext

I have a linq table "KUND" who is read only to me. 我有一个只读给我的linq表“KUND”。 It has some special characters in it to which i have writter a function to switch them out to the ones i want. 它有一些特殊的字符,我已经写了一个功能,将它们切换到我想要的。

public static string changeSpecialCharacters(string kund)
    {
        StringBuilder b = new StringBuilder(kund);

        b = b.Replace("Õ", "å");
        b = b.Replace("┼", "Å");
        b = b.Replace("õ", "ä");
        b = b.Replace("─", "Ä");
        b = b.Replace("÷", "ö");
        b = b.Replace("Í", "Ö");
        b = b.Replace("'", " ");
        b = b.Replace("¦", "´");
        b = b.Replace("Ï", "Ø");

        return b.ToString();
    }

I now have two questions: 我现在有两个问题:

1 Can i add this function to the GET in the autogenerated datacontext so i dont have to call it all over my code? 1我可以在自动生成的datacontext中将此函数添加到GET中,所以我不必在我的代码中调用它吗? Ive added it but it seems to be deleted whenever i change how my datacontext is (add/remove table). 我添加了它,但每当我改变我的datacontext(添加/删除表)时它似乎被删除。 2 Any suggestions how to make that function better in regards to speed perhaps? 2有关如何在速度方面提高功能的建议吗?

Never edit the .designer.cs; 永远不要编辑.designer.cs; instead, add a second file, and use partial class to add the method, for example: 相反,添加第二个文件,并使用partial class添加方法,例如:

namespace Your.Namespace
{
    partial class YourDataContext
    {
        // your methods here
    }
}

No; 没有; you can't add this to the get. 你不能把这个添加到get。 Another alternative, though, is an extension method: 但另一种选择是扩展方法:

namespace Some.Utility.Namespace
{
    public static class SomeUtilityClass
    {
        public static string ChangeSpecialCharacters(this string kund)
        { ... } // note the "this" in the above line
    }
}

Now you can use: 现在你可以使用:

string name = obj.Name.ChangeSpecialCharacters();

personally I would rename this to clarify the direction of the change, and have two methods - one to encode, one to decode. 我个人会重命名这个以澄清变化的方向 ,并有两个方法 - 一个编码,一个解码。


Re doing this for a set of data; 为一组数据做这个; perhaps: 也许:

public static IEnumerable<SomeType> ChangeSpecialCharacters(
    this IEnumerable<SomeType> items)
{
    foreach(var item in items)
    {
        item.Name = item.Name.ChangeSpecialCharacters();
        item.Foo = item.Foo.ChangeSpecialCharacters();
        ...
        item.Bar = item.Bar.ChangeSpecialCharacters();
        yield return item;
    }
}

probably you could initialize your variable as: 可能你可以将你的变量初始化为:

private string kund;
public string Kund
{
    get
    {
        return changeSpecialCharacters(string kund);
    }
    set
    {
        kund = value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM