Improve code: Compare 2 item lists

Sorry for the beginners question, but I'm new to programming.

I want to check if there is listOfDifferentTypesno more than one element TypeA. I have a code:

     public void CheckType ( Object param)
     {
            if ( param is TypeA )
            {
                int i = 0;
                TypeA paramToCheck = ( TypeA ) param;

                foreach ( var paramB in listOfDifferentTypes )
                {
                    if ( paramB is TypeA )
                    {
                        var paramInList = ( TypeA ) paramB;
                        if ( paramToCheck.ID == paramInList.ID )
                        {
                            i++;
                        }
                    }
                }
                if ( i > 1 )
                {
                    paramToCheck.m_Error = "ErrorText";
                }    
            }
    }

I think this is not a very clean solution. Can this code be improved / optimized?

+3
source share
2 answers

You can use LINQ for this :) It will look good:

//Checks for string - resplace <string> with <some type> for other types
private bool moreThanOne(List<object> differentTypes)
{
    return differentTypes.OfType<string>().Count() > 1;
}

Using:

List<object> listOfDifferentTypes = new List<object> { "string", 13, 52, "string", 54.3f };

var res = moreThanOne(listOfDifferentTypes);

I see that you are also checking some sort of identifier, and then try the following:

UPDATED to do what your code does

Updated: replaced .Count () with .Skip (1) .Any (), so it will stop if more than 1 is found :)

private void CheckType(object param, List<object> differentTypes)
{
    var paramToCheck = param as TypeA;

    if (paramToCheck == null) return;

    var res = differentTypes.OfType<TypeA>().Where(t => t.ID == paramToCheck.ID).Skip(1).Any();

    if (res) paramToCheck.m_Error = "error text";
}

As I have already done, you can replace:

if (param is TypeA)
{
    TypeA paramToCheck = (TypeA) param;
    ... Do something

WITH

TypeA paramToCheck = param as TypeA; //Returns null if not a TypeA
if (param == null) return;

... Do something

This is a little faster :)

+2

, :

public void CheckType(Object param)
{
   TypeA paramToCheck = param as TypeA;
   int count = 0;
   if (paramToCheck != null)
   {
       foreach (var paramB in listOfDifferentTypes)
       {
           var paramInList = paramB as TypeA;
           if (paramInList != null && paramToCheck.ID == paramInList.ID)
           {
               count++;

               if (count > 1)
               {
                   paramToCheck.m_Error = "ErrorText";
                   break;
               }
           }
       }
   }

}

:

  • as null ,
  • if ( AND (&&)),
  • break foreach, .
  • ; : -)

: re: comments (, !)

+1

Source: https://habr.com/ru/post/1757970/


All Articles