어떻게 수행 FindAll()명령에<T>?(예를 들어.다음 코드 예제에서는 만들.값)

StackOverflow https://stackoverflow.com/questions/617374

  •  03-07-2019
  •  | 
  •  

문제

에서 일하고 있어요 문제에서는 C#2.0/.NET2.0 어디서 나는 다음 코드 예제에서는 만들고 검색하려는 모든"값"(지 않는"키를")의 이 다음 코드 예제에서는 만들에 대한 특정 문자열과 횟수는 얼마나 많은 사건이 있습니다.

이것은 무엇을 하려고 해요 하:

{
   Sortedlist<string,string> mySortedList;
   // some code that instantiates mySortedList and populates it with data
   List<string> myValues = mySortedList.Values;  // <== does not work
   int namesFound = myValues.FindAll(ByName(someName)).Count;
}

당연히,이 작동하지 않기 때문에 mySortedList.값을 반환하는 명령하는 동안,"myValues"목록입니다.나"주"명령 될 수 있도록 허용 myValues 지만,그것은 작동하지 않는 것.

물론,내가 할 수 있습 반복 mySortedList.값이"foreach"루프,하지만 내가 정말 원하지 않습니다.

누군가가 어떤 제안이 있는가?

편집-1:확인을 잘 보이지 않는 기본 방법을 이렇게 쉽습니다.나는 생각했다 내가 누락 무언가를하지만,분명히 나가지 않습니다.그래서 나가 그냥을 할거야"foreach"이 명령.

감사에 대한 피드백을 모두!저는 투표를 모두 1 다고 생각하기 때문에 모든 의견을 좋았습니다.다시 한번 감사드립니다!:-)

편집-2:보 CMS 답을 찾고 있었습니다.주의해야 할 점이(로 Qwertie 지적)이 있는 잠재적으로 성능이 저하므로 복사하는 것을 포함한 모든 값을 다른 목록과 그 검색 목록이 시작입니다.그래서 짧은 목,이 대답은 효과적입니다.이 목록은?잘 결정하는 당신까지...

도움이 되었습니까?

해결책

이후 명령 인터페이스 를 구현하는 , 할 수 있습니다 실제로 얻 List<T> 의 값을 사용하여 List<T> (IEnumerable) Constructor:

List<string> myValues = new List<string>(mySortedList.Values);

다른 팁

할 수 없습니다 캐스팅 값을 속성을 목록<string> 지 않기 때문에 목록<string>-그것은 사전<TKey, TValue="">.ValueCollection.

그러나 사용하는 경우 LinqBridge (습니다.NET Framework2.0C#3.0),이 문제는 쉽게 해결된 LINQ 는 다음과 같다:

SortedList<string, string> m = ...;
int namesFound = m.Values.Where(v => v.Contains("substring")).Count();

(있을 경우 당신은 여전히 C#2.0 을 사용할 수 있습니다 가난한 사람의 LINQ 대신,약간 더 일)

너무 나쁜할 수 있습니다.Net2.0.이 LINQ 에는 것입니다.;)

할 수 없습니다 정말로 이렇게,이후 FindAll()는 회원의 목록입니다.을 만들 수 있습니다 새로운 목록에서 mySortedList.값지만,그것은 있을 것 같 낭비 때문에,새로운 객체 및 내부 배열해야 할당을 함수를 호출.

나는 그를 쓰는 유틸리티 기능에 일부에 대해 클래스 목록이라는 FindAll()및 그 후 통과하는 명령하고할 수 있습니다.

을 시도했다 SortedListko GetValueList 아직?이 당신에게 다시 IList 의 값이 있습니다.

    static void Main(string[] args)
    {
        string someName = "two";
        SortedList<string, string> mySortedList = new SortedList<string,string>()
        {
            {"key1", "This is key one"},
            {"key2", "This is key two"},
            {"key3", "This is key three"},
        };

        int namesFound = mySortedList.Values.Where(i => i.Contains(someName)).Count();
        Console.WriteLine(namesFound);
        Console.ReadKey();
    }

에 Framework2.0,어쩌면 작업을 수행 할 수 있습니다:

    static void Main(string[] args)
    {
        string someName = "two";
        SortedList<string, string> mySortedList = new SortedList<string,string>()
        {
            {"key1", "This is key one"},
            {"key2", "This is key two"},
            {"key3", "This is key three"},
        };

        int namesFound = FindAll(mySortedList.Values, someName).Count ;
        Console.WriteLine(namesFound);
        Console.ReadKey();
    }
    public static IList<String> FindAll(IList<String> items, string item)
    {
        List<String> result = new List<string>();
        foreach (String s in items)
        {
            if (s.Contains(item))
            {
                result.Add(s);
            }
        }
        return result;
    }

하지만 그건 당신이 정말 하고 싶지 않았다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top