본문으로 건너뛰기

[Codewars #53] List Filtering (7kyu)

· 약 1분
karais89

Instructions

링크

In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

Example

ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b"}) => {1, 2}
ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b", 0, 15}) => {1, 2, 0, 15}
ListFilterer.GetIntegersFromList(new List<object>(){1, 2, "a", "b", "aasf", "1", "123", 231}) => {1, 2, 231}

My Solution

using System.Collections;
using System.Collections.Generic;

public class ListFilterer
{
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
{
List<int> newInts = new List<int>();
foreach (var item in listOfItems)
{
if (item is int)
{
newInts.Add((int)item);
}
}
return newInts;
}
}
  • c# 자료형 판단? 리플렉션을 사용해야 되나?
  • is 연산자로 가능?
  • newInts 말고 filterInts 정도로 네이밍 변경을 했으면 좋았겠다.

Best Practices

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class ListFilterer
{
public static IEnumerable<int> GetIntegersFromList(List<object> listOfItems)
{
return listOfItems.OfType<int>();
}
}