2014-02-09 48 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); 
    } 
} 
相关问题