2013-05-29 2 views
0

SQLite 데이터베이스의 모든 테이블을 나열하려고하지만 시스템 테이블이 아닌 일반 테이블 만 필요합니다. foreach를 사용하여이 작업을 시도하고 루핑하는 동안 행을 제거했지만 예외가 발생합니다. 내가 틀린 곳을 실제로 보지 않기 때문에 누구나 내가 잘못하고있는 것을 지적 해 주실 수 있습니까?DataTable에서 DataRow를 제거 할 수 없습니다.

내 유일한 생각은 루핑하는 동안 DataTable에서 제거 할 수 없다는 것이지만이 문제에 어떻게 다르게 접근 할 것인지 잘 모릅니다.

데이터베이스는 현재 4 개 테이블, 정상 3 1 시스템 테이블을 포함

코드 :

 SQLiteConnection connection = new SQLiteConnection("Data Source=db.sqlite"); 

     connection.Open(); 

     DbTables = connection.GetSchema("Tables"); 

     foreach (DataRow row in DbTables.Rows) 
     { 
      Console.WriteLine(row[3].ToString()); 

      if (row[3].ToString() == "SYSTEM_TABLE") 
       DbTables.Rows.Remove(row); 
     } 

     connection.Close(); 

예외 :

:

System.Windows.Data Error: 17 : Cannot get 'Main' value (type 'MainViewModel') from '' (type 'ViewModelLocator'). BindingExpression:Path=Main; DataItem='ViewModelLocator' (HashCode=65325907); target element is 'MainWindow' (Name=''); target property is 'DataContext' (type 'Object') TargetInvocationException:'System.Reflection.TargetInvocationException: Property accessor 'Main' on object 'DatabaseExplorer.ViewModel.ViewModelLocator' threw the following exception:'Exception has been thrown by the target of an invocation.' ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Collection was modified; enumeration operation might not execute. 
    at System.Data.RBTree`1.RBTreeEnumerator.MoveNext() 
    at DatabaseExplorer.ViewModel.MainViewModel..ctor(IDataService dataService) in Project\ViewModel\MainViewModel.cs:line 61 
    --- End of inner exception stack trace --- 
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 
    at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
    at System.Reflection.ConstructorInfo.Invoke(Object[] parameters) 
    at GalaSoft.MvvmLight.Ioc.SimpleIoc.MakeInstance[TClass]() 
    --- End of inner exception stack trace --- 
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 
    at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) 
    at System.Delegate.DynamicInvokeImpl(Object[] args) 
    at System.Delegate.DynamicInvoke(Object[] args) 
    at GalaSoft.MvvmLight.Ioc.SimpleIoc.DoGetService(Type serviceType, String key) 
    at GalaSoft.MvvmLight.Ioc.SimpleIoc.GetInstance[TService]() 
    at DatabaseExplorer.ViewModel.ViewModelLocator.get_Main() in Project\ViewModel\ViewModelLocator.cs:line 54 
    --- End of inner exception stack trace --- 
    at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) 
    at MS.Internal.Data.ValueTable.GetValue(Object item, PropertyDescriptor pd, Boolean indexerIsNext) 
    at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level) 
    at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)' 

콘솔 출력이 나는 경우 절을 제거

SYSTEM_TABLE 
table 
table 
table 

미리 감사드립니다!

답변

3

컬렉션을 열거하는 동안 컬렉션을 수정할 수 없습니다. 따라서 foreach 루프를 for으로 변경하거나 제거 할 행으로 채워지고 나중에 제거 할 임시 컬렉션을 만들 수 있습니다.

첫 번째 방법 (나는 지금 내 컴퓨터 앞에 아니에요, 테스트 필요) :

for (int i = DbTables.Rows.Count; i >=0 ; i--) 
{ 
    if (DbTables.Rows[i].ToString() == "SYSTEM_TABLE") 
     DbTables.Rows.RemoveAt(i); 
} 

두 번째 방법 :

DbTables = connection.GetSchema("Tables"); 

var rowsToBeRemoved = new List<DataRow>(); 

foreach (DataRow row in DbTables.Rows) 
{ 
    Console.WriteLine(row[3].ToString()); 

    if (row[3].ToString() == "SYSTEM_TABLE") 
     rowsToBeRemoved.Add(row); 
} 

foreach DataRow row in rowsToBeRemoved) 
{ 
    DbTables.Rows.Remove(row); 
} 
+0

그래 당신이, 내가 완전히 바로 읽을 수있는 직후에이 나는 테이블 이름 만 필요로한다는 것을 기억합니다. 나는 그들을 제거 할 필요가 없습니다. 목록에 일반 테이블을 저장해야합니다. 시간을 낭비하게되어서 죄송합니다. 어쨌든 도움을 주셔서 감사합니다! 대단히 감사합니다! – Kryptoxx

+0

아무런 문제가 없지만 항상 조금이라도 도움이되어서 기쁩니다. :) – gzaxx

관련 문제