用lambda替换foreach

时间:2013-09-06 07:01:22

标签: c#

有人可以帮助我用以下两种方法替换foreach和lambda,或者其他任何优化都将受到赞赏。

/// <summary>
/// This method will find and remove the Template entries that has no person entris
/// from List<Template> Templates
/// </summary>
/// <param name="Persons"></param>
/// <param name="Templates"></param>
public bool ClearOrphnedIDs(List<Person> Persons, List<Template> Templates)
{
    bool isClearComplete = false;
    try
    {
        if (Persons != null && Templates != null)
        {
            List<string> OrphnedTemplatesNeedToIgnore = new List<string>();
            foreach (Template template in Templates)
            {
                string personID = Persons.Find(p => p.PersonID == template.PersonID).PersonID;
                if (string.IsNullOrEmpty(personID) && !OrphnedTemplatesNeedToIgnore.Contains(personID))
                {
                        OrphnedTemplatesNeedToIgnore.Add(template.PersonID);
                        DataSyncLog.Warn(string.Format("Templates with personID {0} is orphned (has no person entry) in DB", template.PersonID));
                }

            }
            if (OrphnedTemplatesNeedToIgnore.Count > 0)
                Templates.RemoveAll(t=> OrphnedTemplatesNeedToIgnore.Contains(t.PersonID));
            isClearComplete = true;
        }
    }
    catch (Exception ex)
    {
        DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + " :: " + ex.Message + " :: " + ex.StackTrace);
    }
    return isClearComplete;
}

/// <summary>
/// This method will Find and remove the Person and template entries that has 
/// zero or odd number of templates. from List<Person> Persons and List<Template> Templates
/// </summary>
/// <param name="Persons"></param>
/// <param name="Templates"></param>
public bool ClearInconsistantIDs(List<Person> Persons, List<Template> Templates)
{
    bool isClearComplete = false;
    try
    {
        if (Persons != null && Templates != null)
        {
            List<string> personNeedtoIgnoreAlongWithItsTemplates = new List<string>();
            foreach (Person person in Persons)
            {
                int templatesCount = Templates.FindAll(t => t.PersonID == person.PersonID).Count;
                if (templatesCount == 0 || templatesCount % 2 != 0)
                {
                    personNeedtoIgnoreAlongWithItsTemplates.Add(person.PersonID);
                    if (templatesCount == 0)
                        DataSyncLog.Warn(string.Format("Person with Registration No: {0} and personID {1} has no Templates in DB. Templates Count: {2}", person.RegistrationNO, person.PersonID, templatesCount));
                    else
                        DataSyncLog.Warn(string.Format("Person with Registration No: {0} and personID {1} has inconsistent data (Templates) in DB. Templates Count: {2}", person.RegistrationNO, person.PersonID, templatesCount));

                }
            }
            if (personNeedtoIgnoreAlongWithItsTemplates.Count > 0)
            {
                Templates.RemoveAll(t => personNeedtoIgnoreAlongWithItsTemplates.Contains(t.PersonID));
                Persons.RemoveAll(p => personNeedtoIgnoreAlongWithItsTemplates.Contains(p.PersonID));
            }
            isClearComplete = true;
        }

    }
    catch (Exception ex)
    {
        DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + " :: " + ex.Message + " :: " + ex.StackTrace);
    }
    return isClearComplete;
}

3 个答案:

答案 0 :(得分:4)

我不认为你可以用lambda做得更好,但是你绝对可以使用HashSet<string>而不是List<string>做更好的事情,并为HashSet<string>的{​​{1}}值制作另一个PersonID Persons参数:

public bool ClearOrphnedIDs(List<Person> Persons, List<Template> Templates)
{
    bool isClearComplete = false;
    try
    {
        if (Persons != null && Templates != null)
        {
            var personsSet = new HashSet<string>(Persons.Select(p => p.PersonId));
            var orphnedTemplatesNeedToIgnore = new HastSet<string>();
            foreach (var template in Templates)
            {
                if (!personsSet.Contains(template.PersonID) && !orphnedTemplatesNeedToIgnore.Contains(personID))
                {
                        orphnedTemplatesNeedToIgnore.Add(template.PersonID);
                        DataSyncLog.Warn(string.Format("Templates with personID {0} is orphned (has no person entry) in DB", template.PersonID));
                }

            }
            if (orphnedTemplatesNeedToIgnore.Count > 0)
                Templates.RemoveAll(t => orphnedTemplatesNeedToIgnore.Contains(t.PersonID));
            isClearComplete = true;
        }
    }
    catch (Exception ex)
    {
        DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + " :: " + ex.Message + " :: " + ex.StackTrace);
    }
    return isClearComplete;
}

答案 1 :(得分:1)

我会定义一个扩展方法ExceptBy

var result = Templates.ExceptBy(Persons, t => t.PersonID, p => p.PersonID)
                      .ToList();

public static IEnumerable<TSource> ExceptBy<TSource, TKey, TDest>(
        this IEnumerable<TSource> first,
        IEnumerable<TDest> second,
        Func<TSource, TKey> keySelector1,
        Func<TDest, TKey> keySelector2)
{
    HashSet<TKey> keys = new HashSet<TKey>(second.Select(keySelector2));

    return first.Where(k => keys.Add(keySelector1(k)));
}

答案 2 :(得分:0)

伙计们怎么样,

/// <summary>
    /// This method will find and remove the Template entries that has no person entris
    /// from List<Template> Templates
    /// </summary>
    /// <param name="Persons"></param>
    /// <param name="Templates"></param>
    public bool ClearOrphnedIDs(List<Person> Persons, List<Template> Templates)
    {
        bool isClearComplete = false;
        try
        {
            if (Persons != null && Templates != null)
            {
                HashSet<string> personsSet = new HashSet<string>(Persons.Select(p => p.PersonID));
                Templates.RemoveAll(t => !personsSet.Contains(t.PersonID));
                isClearComplete = true;
            }
        }
        catch (Exception ex)
        {
            DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + " :: " + ex.Message + " :: " + ex.StackTrace);
        }
        return isClearComplete;
    }

    /// <summary>
    /// This method will Find and remove the Person and template entries that has 
    /// zero or odd number of templates. from List<Person> Persons and List<Template> Templates
    /// </summary>
    /// <param name="Persons"></param>
    /// <param name="Templates"></param>
    public bool ClearInconsistantIDs(List<Person> Persons, List<Template> Templates)
    {
        bool isClearComplete = false;
        try
        {
            if (Persons != null && Templates != null)
            {
                HashSet<string> inconsistantIDs = new HashSet<string>(
                  Persons.Select(p => p.PersonID).Where(p =>
                  {
                      var count = Templates.Count(t => t.PersonID == p);
                      return count == 0 || count % 2 != 0;
                  }
                  ));

                if (inconsistantIDs.Count > 0)
                {
                    Templates.RemoveAll(t => inconsistantIDs.Contains(t.PersonID));
                    Persons.RemoveAll(p => inconsistantIDs.Contains(p.PersonID));
                }
                isClearComplete = true;
            }

        }
        catch (Exception ex)
        {
            DataSyncLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + " :: " + ex.Message + " :: " + ex.StackTrace);
        }
        return isClearComplete;
    }