2014-02-09 77 views
1

我不是VB的粉絲。任何人都可以幫助我在c#中創建這段代碼嗎?什麼是VB Linq中Aggregate關鍵字的C#等價物?

Public ReadOnly Property HasErrors() As Boolean 
     Get 
      Return (Aggregate o In Me _ 
        Let errObj = TryCast(o, IDataErrorInfo) _ 
        Where If(errObj IsNot Nothing, errObj.Error <> Nothing, False) _ 
        Into Count()) > 0 
     End Get 
    End Property 

更新

Public MustInherit Class MyBaseCollection(Of T) 
    Inherits ObservableCollection(Of T) 

    Public ReadOnly Property HasErrors() As Boolean 
     Get 
      Return (Aggregate o In Me _ 
        Let errObj = TryCast(o, IDataErrorInfo) _ 
        Where If(errObj IsNot Nothing, errObj.Error <> Nothing, False) _ 
        Into Count()) > 0 
     End Get 
    End Property 

    Sub New(ByVal query As IEnumerable(Of T), ByVal context As OMSEntities) 
     MyBase.New(query) 
    End Sub 

End Class 
+0

我嘗試使用在線代碼轉換它來轉換。但是我最終得到了未編譯的代碼。 – sovantha

回答

0

我不是100%的這是什麼,但我認爲你可以做它與

this.Any(o => { 
    var errObj = o as IDataErrorInfo; 
    return errObj != null && errObj.Error != null 
}); 

,或者你可以做更多的功能性風格:

this.Select(o => o as IDataErrorInfo) 
    .Any(errObj => errObj != null && errObj.Error != null); 
+0

C#中沒有'TryCast'。 http://stackoverflow.com/questions/3350770/how-to-convert-trycast-in-c – MarcinJuraszek

+0

@MarcinJuraszek啊,我認爲這是他自己的功能,在這種情況下,我們可以使用'as' –

1

有在C#基於語法的查詢沒有類似Aggregate。你必須使用方法。

public bool HasErrors 
{ 
    get 
    { 
     return this.Select(x => x as IDataErrorInfo) 
        .Where(x => x != null && x.Error != null) 
        .Count() > 0; 
    } 
} 

或更容易版本Count(predicate)超載:

public bool HasErrors 
{ 
    get 
    { 
     return this.Select(x => x as IDataErrorInfo) 
        .Count(x => x != null && x.Error != null) > 0; 
    } 
} 
Any(predicate)

甚至更​​好:

public bool HasErrors 
{ 
    get 
    { 
     return this.Select(x => x as IDataErrorInfo) 
        .Any(x => x != null && x.Error != null); 
    } 
} 
0

這不是準確的翻譯,但它會得到相同的結果:

public bool HasErrors 
{ 
    get 
    { 
     return this.OfType<IDataErrorInfo>().Any(x => x.Error != null); 
    } 
} 
相關問題