2013-04-23 3 views
1

DBContext와 함께 최신 Entity Framework를 사용하고 있습니다. 쉼표로 구분 된 값으로 변환하려는 결과 세트가 있습니다. VB에서 DataTables과 비슷한 작업을했습니다 DataTable to CSV extraction. QuoteName 메서드가 작동하고 있습니다. foreach를 사용하여 GetCSV 메서드의 파생물을 얻었습니다. 문제는 DataTable의 비슷한 코드보다 훨씬 느리다는 것입니다. 그래서 나는 누군가가 약간의 제안을하기를 희망하고있다..Net Entity Framework to CSV

public static string GetCSV(this IQueryable entity) 
    { 
     if (entity == null) 
     { 
      throw new ArgumentNullException("entity"); 
     } 
     Type T = entity.ElementType; 
     var props = T.GetProperties(BindingFlags.Public | BindingFlags.Instance); 
     string s = string.Empty; 
     int iCols = props.Count(); 

     try 
     { 
      s += string.Join(",", (from int ii in Enumerable.Range(0, iCols) 
            select props[ii].Name.QuoteName("[]")).ToArray()); 
      s += Environment.NewLine; 
      foreach (var dr in entity) 
      { 
       s += string.Join(",", (from int ii in Enumerable.Range(0, iCols) 
             select 
              props[ii].GetValue(dr) 
                .ToString() 
                .QuoteName("\"\"", ",")).ToArray()); 
       s += Environment.NewLine; 
      } 
      s = s.TrimEnd(new char[] { (char)0x0A, (char)0x0D }); 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
     return s; 
    } 
+0

안녕하세요,이 구현하려고하지만 컴파일러는 Quotename 함수를 인식하지 못합니다. 어떻게 이것을 수행 할 수 있습니까? –

답변

2

문자열을 사용하여 파일을 만들지 마십시오. StringBuilder 클래스 사용 (http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx)

문자열은 변경 불가능한 개체입니다. 즉, 문자열을 만든 후에는 변경할 수 없습니다. 문자열을 연결할 때마다 (연결하는 경우와 같이) 실제로 새로운 문자열을 만듭니다. 문자열을 사용하면 매우 비효율적입니다. 단지

builder.ToString(); 
0

에서 사용의 예입니다. 그는 StringBuilder도 사용하라고했습니다. 나는이 다른 사람에게 도움이 희망

/// <summary> 
    /// Quotes a string using the following rules: 
    /// <list> 
    /// <listheader>Rules</listheader> 
    /// <item>if the string is not quoted and the string contains the separator string</item> 
    /// <item>if the string is not quoted and the string begins or ends with a space</item> 
    /// <item>if the string is not quoted and the string contains CrLf</item> 
    /// </list> 
    /// </summary> 
    /// <param name="s">String to be quoted</param> 
    /// <param name="quote"> 
    /// <list> 
    /// <listheader>quote characters</listheader> 
    /// <item>if len = 0 then double quotes assumed</item> 
    /// <item>if len = 1 then quote string is doubled for left and right quote characters</item> 
    /// <item>else first character is left quote, second character is right quote</item> 
    /// </list> 
    /// </param> 
    /// <param name="sep">separator string to check against</param> 
    /// <returns></returns> 
    /// <remarks></remarks> 
    public static string QuoteName(this string s, string quote = null, string sep = ",") 
    { 
     quote = quote == null ? "" : quote; 
     switch (quote.Length) 
     { 
      case 0: 
       quote = "\"\""; 
       break; 
      case 1: 
       quote += quote; 
       break; 
     } 
     // Fields with embedded sep are quoted 
     if ((!s.StartsWith(quote.Substring(0, 1))) && (!s.EndsWith(quote.Substring(1, 1)))) 
      if (s.Contains(sep)) 
       s = quote.Substring(0, 1) + s + quote.Substring(1, 1); 
     // Fields with leading or trailing blanks are quoted 
     if ((!s.StartsWith(quote.Substring(0, 1))) && (!s.EndsWith(quote.Substring(1, 1)))) 
      if (s.StartsWith(" ") || s.EndsWith(" ")) 
       s = quote.Substring(0, 1) + s + quote.Substring(1, 1); 
     // Fields with embedded CrLF are quoted 
     if ((!s.StartsWith(quote.Substring(0, 1))) && (!s.EndsWith(quote.Substring(1, 1)))) 
      if (s.Contains(System.Environment.NewLine)) 
       s = quote.Substring(0, 1) + s + quote.Substring(1, 1); 
     return s; 
    } 

    public static string GetCSV(this IQueryable entity) 
    { 
     if (entity == null) 
     { 
      throw new ArgumentNullException("entity"); 
     } 
     Type T = entity.ElementType; 
     var props = T.GetProperties(BindingFlags.Public | BindingFlags.Instance); 
     var sb = new StringBuilder(); 
     int iCols = props.Count(); 

     try 
     { 
      sb.Append(string.Join(",", Enumerable.Range(0, iCols).Cast<int>(). 
       Select(ii => props[ii].Name.QuoteName("[]")).ToArray())); 

      foreach (var dr in entity) 
      { 
       sb.AppendLine(); 
       sb.Append(string.Join(",", Enumerable.Range(0, iCols).Cast<int>(). 
        Select(ii => props[ii].GetValue(dr). 
         ToString().QuoteName("\"\"", ",")).ToArray())); 
      } 
     } 
     catch (Exception ex) 
     { 

      throw; 
     } 
     return sb.ToString(); 
    } 
} 

:

코드의 답변입니다.

관련 문제