VB Linq中Aggregate关键字的C#等价是什么?

时间:2014-02-09 04:09:35

标签: c# vb.net linq

我不是VB的忠实粉丝。任何人都可以帮我在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

3 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

我不是百分之百的,但我觉得你可以用

来做
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);

答案 2 :(得分:0)

这不是确切的翻译,但它会得到相同的结果:

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