문제

ASP.NET 페이지에서 확인 된 확인란을 찾고 싶다면 다음 LINQ 쿼리를 사용할 수 있습니다.

var checkBoxes = this.Controls
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

확인란이 현재 제어 컬렉션에 중첩되면 제대로 작동하지만 최상위 컨트롤의 제어 컬렉션으로 드릴링하여 검색을 확장하는 방법을 알고 싶습니다.

질문은 여기에 다음과 같습니다.

ASP.NET에서 특정 인터페이스를 사용하는 컨트롤을 찾습니다

LINQ가 아닌 답변을 받았는데, 이미 유형 및 ID에 대한 재귀 제어 검색 버전을 확장 방법으로 가지고 있지만 LINQ에서 이것이 얼마나 쉬운 지 궁금했습니다.

도움이 되었습니까?

해결책

재귀에서 유형/ID를 확인하십시오. 따라서 "모든 컨트롤을 줘, 재귀 적으로 나에게"방법, 예를 들어

public static IEnumerable<Control> GetAllControls(this Control parent)
{
    foreach (Control control in parent.Controls)
    {
        yield return control;
        foreach(Control descendant in control.GetAllControls())
        {
            yield return descendant;
        }
    }
}

그것은 다소 비효율적이지만 (많은 반복자를 만드는 측면에서) 나는 당신이 매우 깊은 나무.

그런 다음 원래 쿼리를 다음과 같이 쓸 수 있습니다.

var checkBoxes = this.GetAllControls()
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

(편집 : AllControls를 변경하여 ALLCONTROLS로 변경하여 방법으로 올바르게 사용하십시오.)

다른 팁

public static IEnumerable<Control> AllControls(this Control container)
{
    //Get all controls
    var controls = container.Controls.Cast<Control>();

    //Get all children
    var children = controls.Select(c => c.AllControls());

    //combine controls and children
    var firstGen = controls.Concat(children.SelectMany(b => b));

    return firstGen;
}

이제 위의 기능을 기반으로 다음과 같은 작업을 수행 할 수 있습니다.

public static Control FindControl(this Control container, string Id)
{
    var child = container.AllControls().FirstOrDefault(c => c.ID == Id);
    return child;
}

내 제안을 만들기위한 나의 제안 AllControls 재귀는 다음과 같습니다.

    public static IEnumerable<Control> AllControls(this Control parent)
    {
        foreach (Control control in parent.Controls)
        {
             yield return control;
        }
        foreach (Control control in parent.Controls)
        {
            foreach (Control cc in AllControls(control)) yield return cc;
        }
    }

두번째 foreach 이상하게 보이지만 이것은 재귀 호출을 "평평하게"하는 유일한 방법입니다.

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