본문 바로가기
Study/C#

C# Windows Forms 강의 21편: LINQ를 활용한 데이터 검색과 필터링

by wawManager 2025. 2. 24.
728x90

1. 강의 개요

이번 강의에서는 **LINQ(Language Integrated Query)**를 활용하여 데이터를 효율적으로 검색, 필터링, 정렬하는 방법을 학습합니다.
LINQ는 C#에서 데이터 컬렉션(Array, List, Dictionary 등) 또는 데이터베이스(SQL)와 상호작용하기 위한 강력한 도구입니다.


2. 학습 목표

  1. LINQ를 사용하여 List 데이터를 필터링하고 검색.
  2. LINQ로 데이터를 정렬하고 그룹화.
  3. Windows Forms에서 LINQ 결과를 UI에 표시.

3. LINQ란?

LINQ는 컬렉션 데이터를 쿼리 형식으로 처리할 수 있는 C#의 기능입니다.

  • SQL과 유사한 문법을 제공.
  • 컬렉션 데이터를 읽기, 필터링, 정렬, 그룹화하는 데 유용.

LINQ 주요 연산자

연산자 설명 예제

Where 조건에 맞는 데이터를 필터링 list.Where(x => x.Age > 20);
OrderBy 데이터를 오름차순 정렬 list.OrderBy(x => x.Name);
OrderByDescending 데이터를 내림차순 정렬 list.OrderByDescending(x => x.Age);
Select 특정 데이터를 선택 list.Select(x => x.Name);
GroupBy 데이터를 그룹화 list.GroupBy(x => x.Category);

4. 실습: LINQ를 활용한 데이터 검색 및 필터링

요구사항

  1. List 데이터에서 이름, 나이, 직업을 필터링.
  2. 나이에 따라 데이터를 정렬.
  3. 조건에 맞는 데이터를 ListBox에 표시.

폼 구성

컨트롤 타입 이름 텍스트 위치 크기

Label lblFilter "나이 필터 (20 이상):" (20, 20) (150 x 20)
TextBox txtAgeFilter "20" (180, 20) (50 x 20)
Button btnFilter "필터 적용" (250, 20) (100 x 30)
ListBox listBoxResults (없음) (20, 60) (400 x 200)

데이터 클래스

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Job { get; set; }
}

코드 작성

Form1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private List<Person> people = new List<Person>();

        public Form1()
        {
            InitializeComponent();
            InitializeData();
        }

        private void InitializeData()
        {
            // 데이터 초기화
            people.Add(new Person { Name = "홍길동", Age = 25, Job = "개발자" });
            people.Add(new Person { Name = "김철수", Age = 30, Job = "디자이너" });
            people.Add(new Person { Name = "이영희", Age = 20, Job = "마케터" });
            people.Add(new Person { Name = "박지민", Age = 35, Job = "매니저" });
            people.Add(new Person { Name = "최유리", Age = 28, Job = "개발자" });

            // 필터 버튼 클릭 이벤트 연결
            btnFilter.Click += BtnFilter_Click;
        }

        private void BtnFilter_Click(object sender, EventArgs e)
        {
            // 필터 조건 설정 (나이)
            if (int.TryParse(txtAgeFilter.Text, out int ageFilter))
            {
                // LINQ로 조건에 맞는 데이터 필터링
                var filteredResults = people
                    .Where(p => p.Age >= ageFilter) // 나이 필터
                    .OrderBy(p => p.Age);          // 나이 오름차순 정렬

                // 결과를 ListBox에 표시
                listBoxResults.Items.Clear();
                foreach (var person in filteredResults)
                {
                    listBoxResults.Items.Add($"{person.Name} - {person.Age}세 - {person.Job}");
                }

                if (!filteredResults.Any())
                {
                    listBoxResults.Items.Add("조건에 맞는 데이터가 없습니다.");
                }
            }
            else
            {
                MessageBox.Show("유효한 나이를 입력하세요.", "입력 오류");
            }
        }
    }
}

Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private Label lblFilter;
        private TextBox txtAgeFilter;
        private Button btnFilter;
        private ListBox listBoxResults;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.lblFilter = new Label();
            this.txtAgeFilter = new TextBox();
            this.btnFilter = new Button();
            this.listBoxResults = new ListBox();
            this.SuspendLayout();

            // lblFilter
            this.lblFilter.AutoSize = true;
            this.lblFilter.Location = new System.Drawing.Point(20, 20);
            this.lblFilter.Name = "lblFilter";
            this.lblFilter.Size = new System.Drawing.Size(150, 20);
            this.lblFilter.TabIndex = 0;
            this.lblFilter.Text = "나이 필터 (20 이상):";

            // txtAgeFilter
            this.txtAgeFilter.Location = new System.Drawing.Point(180, 20);
            this.txtAgeFilter.Name = "txtAgeFilter";
            this.txtAgeFilter.Size = new System.Drawing.Size(50, 27);
            this.txtAgeFilter.TabIndex = 1;

            // btnFilter
            this.btnFilter.Location = new System.Drawing.Point(250, 20);
            this.btnFilter.Name = "btnFilter";
            this.btnFilter.Size = new System.Drawing.Size(100, 30);
            this.btnFilter.TabIndex = 2;
            this.btnFilter.Text = "필터 적용";
            this.btnFilter.UseVisualStyleBackColor = true;

            // listBoxResults
            this.listBoxResults.FormattingEnabled = true;
            this.listBoxResults.ItemHeight = 20;
            this.listBoxResults.Location = new System.Drawing.Point(20, 60);
            this.listBoxResults.Name = "listBoxResults";
            this.listBoxResults.Size = new System.Drawing.Size(400, 200);
            this.listBoxResults.TabIndex = 3;

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(450, 300);
            this.Controls.Add(this.listBoxResults);
            this.Controls.Add(this.btnFilter);
            this.Controls.Add(this.txtAgeFilter);
            this.Controls.Add(this.lblFilter);
            this.Name = "Form1";
            this.Text = "LINQ를 활용한 데이터 필터링";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
}

6. 실행 결과

  1. 기본 데이터 표시
    • "홍길동 - 25세 - 개발자" 등의 데이터가 초기화됩니다.
  2. 필터 적용
    • "나이 필터 (20 이상)" 입력란에 값을 입력 후 "필터 적용" 버튼 클릭.
    • 예: 25 입력 → 나이 25 이상인 데이터가 오름차순으로 정렬되어 ListBox에 표시됩니다.
  3. 결과 예시
  4. 홍길동 - 25세 - 개발자 최유리 - 28세 - 개발자 김철수 - 30세 - 디자이너 박지민 - 35세 - 매니저

7. 주요 개념 요약

  1. LINQ는 데이터를 필터링, 정렬, 선택, 그룹화하는 데 유용한 도구입니다.
  2. Where, OrderBy, Select와 같은 LINQ 연산자를 활용하여 다양한 조건을 처리할 수 있습니다.
  3. LINQ 결과를 ListBox 또는 DataGridView와 같은 컨트롤에 쉽게 바인딩할 수 있습니다.

 

728x90