什么时候应该使用LINQ的C#?什么时候、LINQ

2023-09-03 08:42:39 作者:兄弟情,一生去守护、

我学习C#,我觉得LINQ绝对有趣。但是什么是令人难以置信的我的是,我无法想象一个情景,借此使用LINQ将是一个巨大的帮助,因为它在code真的没有那么难复制LINQ功能。

I'm learning C#, and I find LINQ absolutely interesting. However what is boggling me is, I can't think of a scenario whereby using LINQ would be an immense help, as its really not that hard replicating LINQ features in code.

任何个人经验/建议,你可能会想分享?

Any personal experiences/suggestions you might wanna share?

谢谢!

推荐答案

我发现我使用LINQ几乎任何时候,我将不得不previously写一个循环来填充的容器。我使用LINQ到SQL我的ORM和大量LINQ的其他任何地方。

I find that I'm using LINQ just about any time that I would have previously written a loop to fill a container. I use LINQ to SQL as my ORM and lots of LINQ everywhere else.

下面是一个小片段,我写的是发现,如果一个特定的用户是一组特定的Active Directory的辅助类。注意,这里使用的任何()方法来遍历用户的授权组,直到找到一个与匹配的SID。干净多了code比替代。

Here's a little snippet that I wrote for an Active Directory helper class that finds out if a particular user is an a particular group. Note the use of the Any() method to iterate over the user's authorization groups until it finds one with a matching SID. Much cleaner code than the alternative.

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }
    return user.GetAuthorizationGroups()
               .Any( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 );
}

另一种方法:

Alternative:

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }
    bool inGroup = false;
    foreach (var g in user.GetAuthorizationGroups())
    {
         if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
         {
            inGroup = true;
            break;
         }
    }
    return inGroup;
}

private bool IsInGroup( GroupPrincipal group, UserPrincipal user )
{
    if (group == null || group.Sid == null)
    {
        return false;
    }

    foreach (var g in user.GetAuthorizationGroups())
    {
         if ( g => g.Sid != null && g.Sid.CompareTo( group.Sid ) == 0 )
         {
            return true;
         }
    }
    return false;
}

下面是一个片段,确实对一个仓库,订单搜索,而前10个匹配的业务对象转换成一个视图特定的模型(距离是莱文斯坦编辑距离)的匹配模型的从UNIQUEID参数唯一标识。

Here's a snippet that does a search against a repository, orders, and converts the first 10 matching business objects into a view-specific model (Distance is the Levenshtein edit distance of the matching model's unique id from the uniqueID parameter).

model.Results = this.Repository.FindGuestByUniqueID( uniqueID, withExpired )
                               .OrderBy( g => g.Distance )
                               .Take( 10 )
                               .ToList()
                               .Select( g => new GuestGridModel( g ) );