让我们把你的优秀和最喜欢的扩展方法列一个列表。

要求是必须发布完整的代码,以及如何使用它的示例和解释。

基于对这个主题的高度兴趣,我在Codeplex上建立了一个名为extensionoverflow的开源项目。

请将您的回答标记为接受,以便将代码放入Codeplex项目。

请张贴完整的源代码,而不是一个链接。

Codeplex上新闻:

24.08.2010 Codeplex页面现在在这里:http://extensionoverflow.codeplex.com/

11.11.2008 XmlSerialize / XmlDeserialize现在是实现和单元测试。

11.11.2008仍有发展空间。;-)现在就加入!

11.11.2008第三位贡献者加入了ExtensionOverflow,欢迎加入BKristensen

11.11.2008 FormatWith现在是实现和单元测试。

09.11.2008第二个贡献者加入ExtensionOverflow。欢迎来到chakrit。

我们需要更多的开发人员。: -)

09.11.2008 ThrowIfArgumentIsNull现已在Codeplex上实现和单元测试。


当前回答

Sql server有~2000个参数的限制,如果你有10k个id并想要与它们连接的记录,这是一个痛苦。我写了这些方法,接受批量id列表,并像这样调用:

List<Order> orders = dataContext.Orders.FetchByIds(
  orderIdChunks,
  list => row => list.Contains(row.OrderId)
);

List<Customer> customers = dataContext.Orders.FetchByIds(
  orderIdChunks,
  list => row => list.Contains(row.OrderId),
  row => row.Customer
);

public static List<ResultType> FetchByIds<RecordType, ResultType>(
    this IQueryable<RecordType> querySource,
    List<List<int>> IdChunks,
    Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,
    Expression<Func<RecordType, ResultType>> projectionExpression
    ) where RecordType : class
{
    List<ResultType> result = new List<ResultType>();
    foreach (List<int> chunk in IdChunks)
    {
        Expression<Func<RecordType, bool>> filterExpression =
            filterExpressionGenerator(chunk);

        IQueryable<ResultType> query = querySource
            .Where(filterExpression)
            .Select(projectionExpression);

        List<ResultType> rows = query.ToList();
        result.AddRange(rows);
    }

    return result;
}

public static List<RecordType> FetchByIds<RecordType>(
    this IQueryable<RecordType> querySource,
    List<List<int>> IdChunks,
    Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator
    ) where RecordType : class
{
    Expression<Func<RecordType, RecordType>> identity = r => r;

    return FetchByIds(
        querySource,
        IdChunks,
        filterExpressionGenerator,
        identity
        );
}

其他回答

下面是一个扩展方法,它适应Rick Strahl的代码(以及注释),使您不必在每次将字节数组或文本文件转换为字符串时猜测或阅读其字节顺序标记。

这个代码片段允许你简单地做:

byte[] buffer = File.ReadAllBytes(@"C:\file.txt");
string content = buffer.GetString();

如果你发现任何错误,请添加到评论中。请随意将它包含在Codeplex项目中。

public static class Extensions
{
    /// <summary>
    /// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
    /// Original article: http://www.west-wind.com/WebLog/posts/197245.aspx
    /// </summary>
    /// <param name="buffer">An array of bytes to convert</param>
    /// <returns>The byte as a string.</returns>
    public static string GetString(this byte[] buffer)
    {
        if (buffer == null || buffer.Length == 0)
            return "";

        // Ansi as default
        Encoding encoding = Encoding.Default;       

        /*
            EF BB BF    UTF-8 
            FF FE UTF-16    little endian 
            FE FF UTF-16    big endian 
            FF FE 00 00 UTF-32, little endian 
            00 00 FE FF UTF-32, big-endian 
         */

        if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
            encoding = Encoding.UTF8;
        else if (buffer[0] == 0xfe && buffer[1] == 0xff)
            encoding = Encoding.Unicode;
        else if (buffer[0] == 0xfe && buffer[1] == 0xff)
            encoding = Encoding.BigEndianUnicode; // utf-16be
        else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
            encoding = Encoding.UTF32;
        else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
            encoding = Encoding.UTF7;

        using (MemoryStream stream = new MemoryStream())
        {
            stream.Write(buffer, 0, buffer.Length);
            stream.Seek(0, SeekOrigin.Begin);
            using (StreamReader reader = new StreamReader(stream, encoding))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

ASP。NET中,我使用这些扩展httpessionstate来加载会话中的对象。 它允许您以干净的方式加载会话对象,如果它们不存在,则将创建和初始化它们。 我使用两个扩展方法,如下所示:

private bool CreateMode;
private MyClass SomeClass;

protected override void OnInit (EventArgs e)
{
    CreateMode = Session.GetSessionValue<bool> ("someKey1", () => true);
    SomeClass = Session.GetSessionClass<MyClass> ("someKey2", () => new MyClass () 
    { 
       MyProperty = 123 
    });
}

下面是扩展类:

public static class SessionExtensions    
{
    public delegate object UponCreate ();
    public static T GetSessionClass<T> (this HttpSessionState session, 
       string key, UponCreate uponCreate) where T : class
    {
        if (null == session[key])
        {
            var item = uponCreate () as T;
            session[key] = item;
            return item;
        }
        return session[key] as T;
    }
    public static T GetSessionValue<T> (this HttpSessionState session, 
       string key, UponCreate uponCreate) where T : struct
    {
        if (null == session[key])
        {
            var item = uponCreate();
            session[key] = item;
            return (T)item;
        }
        return (T)session[key];
    }
}

一些方便的字符串助手:

用法:

我讨厌不需要的空格尾随或引导字符串,因为字符串可以采取空值,这可能是棘手的,所以我使用这个:

public bool IsGroup { get { return !this.GroupName.IsNullOrTrimEmpty(); } }

这是另一个扩展方法,我使用一个新的验证框架,我正在试验。你可以看到regex扩展,帮助清理凌乱的regex:

public static bool IsRequiredWithLengthLessThanOrEqualNoSpecial(this String str, int length)
{
    return !str.IsNullOrTrimEmpty() &&
        str.RegexMatch(
            @"^[- \r\n\\\.!:*,@$%&""?\(\)\w']{1,{0}}$".RegexReplace(@"\{0\}", length.ToString()),
            RegexOptions.Multiline) == str;
}

来源:

public static class StringHelpers
{
    /// <summary>
    /// Same as String.IsNullOrEmpty except that
    /// it captures the Empty state for whitespace
    /// strings by Trimming first.
    /// </summary>
    public static bool IsNullOrTrimEmpty(this String helper)
    {
        if (helper == null)
            return true;
        else
            return String.Empty == helper.Trim();
    }

    public static int TrimLength(this String helper)
    {
        return helper.Trim().Length;
    }

    /// <summary>
    /// Returns the matched string from the regex pattern. The
    /// groupName is for named group match values in the form (?<name>group).
    /// </summary>
    public static string RegexMatch(this String helper, string pattern, RegexOptions options, string groupName)
    {
        if (groupName.IsNullOrTrimEmpty())
            return Regex.Match(helper, pattern, options).Value;
        else
            return Regex.Match(helper, pattern, options).Groups[groupName].Value;
    }

    public static string RegexMatch(this String helper, string pattern)
    {
        return RegexMatch(helper, pattern, RegexOptions.None, null);
    }

    public static string RegexMatch(this String helper, string pattern, RegexOptions options)
    {
        return RegexMatch(helper, pattern, options, null);
    }

    public static string RegexMatch(this String helper, string pattern, string groupName)
    {
        return RegexMatch(helper, pattern, RegexOptions.None, groupName);
    }

    /// <summary>
    /// Returns true if there is a match from the regex pattern
    /// </summary>
    public static bool IsRegexMatch(this String helper, string pattern, RegexOptions options)
    {
        return helper.RegexMatch(pattern, options).Length > 0;
    }

    public static bool IsRegexMatch(this String helper, string pattern)
    {
        return helper.IsRegexMatch(pattern, RegexOptions.None);
    }

    /// <summary>
    /// Returns a string where matching patterns are replaced by the replacement string.
    /// </summary>
    /// <param name="pattern">The regex pattern for matching the items to be replaced</param>
    /// <param name="replacement">The string to replace matching items</param>
    /// <returns></returns>
    public static string RegexReplace(this String helper, string pattern, string replacement, RegexOptions options)
    {
        return Regex.Replace(helper, pattern, replacement, options);
    }

    public static string RegexReplace(this String helper, string pattern, string replacement)
    {
        return Regex.Replace(helper, pattern, replacement, RegexOptions.None);
    }
}

我喜欢做很多正则表达式,所以我认为这些比添加using语句和额外的代码来处理命名组更容易。

我最常用的扩展是一个可以格式化字节数组:

/// <summary>
/// Returns a string representation of a byte array.
/// </summary>
/// <param name="bytearray">The byte array to represent.</param>
/// <param name="subdivision">The number of elements per group,
/// or 0 to not restrict it. The default is 0.</param>
/// <param name="subsubdivision">The number of elements per line,
/// or 0 to not restrict it. The default is 0.</param>
/// <param name="divider">The string dividing the individual bytes. The default is " ".</param>
/// <param name="subdivider">The string dividing the groups. The default is "  ".</param>
/// <param name="subsubdivider">The string dividing the lines. The default is "\r\n".</param>
/// <param name="uppercase">Whether the representation is in uppercase hexadecimal.
/// The default is <see langword="true"/>.</param>
/// <param name="prebyte">The string to put before each byte. The default is an empty string.</param>
/// <param name="postbyte">The string to put after each byte. The default is an empty string.</param>
/// <returns>The string representation.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="bytearray"/> is <see langword="null"/>.
/// </exception>
public static string ToArrayString(this byte[] bytearray,
    int subdivision = 0,
    int subsubdivision = 0,
    string divider = " ",
    string subdivider = "  ",
    string subsubdivider = "\r\n",
    bool uppercase = true,
    string prebyte = "",
    string postbyte = "")
{
    #region Contract
    if (bytearray == null)
        throw new ArgumentNullException("bytearray");
    #endregion

    StringBuilder sb = new StringBuilder(
        bytearray.Length * (2 + divider.Length + prebyte.Length + postbyte.Length) +
        (subdivision > 0 ? (bytearray.Length / subdivision) * subdivider.Length : 0) +
        (subsubdivision > 0 ? (bytearray.Length / subsubdivision) * subsubdivider.Length : 0));
    int groupElements = (subdivision > 0 ? subdivision - 1 : -1);
    int lineElements = (subsubdivision > 0 ? subsubdivision - 1 : -1);
    for (long i = 0; i < bytearray.LongLength - 1; i++)
    {
        sb.Append(prebyte);
        sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? "{0:X2}" : "{0:x2}"), bytearray[i]));
        sb.Append(postbyte);

        if (lineElements == 0)
        {
            sb.Append(subsubdivider);
            groupElements = subdivision;
            lineElements = subsubdivision;
        }
        else if (groupElements == 0)
        {
            sb.Append(subdivider);
            groupElements = subdivision;
        }
        else
            sb.Append(divider);

        lineElements--;
        groupElements--;
    }
    sb.Append(prebyte);
    sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? "{0:X2}" : "{0:x2}"), bytearray[bytearray.LongLength - 1]));
    sb.Append(postbyte);

    return sb.ToString();
}

默认情况下,ToArrayString()只是将字节数组打印为由单个字节组成的长字符串。但是,ToArrayString(4,16)将字节分组为4个一组,一行16个字节,就像在您最喜欢的十六进制编辑器中一样。下面很好地格式化了字节数组,以便在c#代码中使用:

byte[] bytearray = new byte[]{ ... };
Console.Write(bytearray.ToArrayString(4, 16, ", ", ",   ", ",\r\n", true, "0x"));

这是我写的,所以你可以用Codeplex。

如果您使用财政年度,则有两个有用的扩展

/// <summary>
/// Returns the fiscal year for the passed in date
/// </summary>
/// <param name="value">the date</param>
/// <returns>the fiscal year</returns>
public static int FiscalYear(this DateTime value)
{
  int ret = value.Year;
  if (value.Month >= 7) ret++;
  return ret;
}

/// <summary>
/// Returns the fiscal year for the passed in date
/// </summary>
/// <param name="value">the date</param>
/// <returns>the fiscal year</returns>
public static string FiscalYearString(this DateTime value)
{
  int fy = FiscalYear(value);
  return "{0}/{1}".Format(fy - 1, fy);
}