Programming/C# - Window

C#/ LINQ(language integrated query)

esoog Polaris 2023. 6. 29. 09:55
using System;
using System.Linq;
// LINQ 네임스페이스를 활용하기 위함
// LINQ 는 데이터 질의 기능
namespace From
{
class MainApp
{
static void Main(string[] args)
{
int[] numbers = { 9, 2, 6, 4, 5, 3, 7, 8, 1, 10 };
var result = from n in numbers
// from 은 모든 LINQ 쿼리식의 시작점. 범위 변수(IEnumerable<T> 상속형식만)
// 2중 from문 가능. 구체 범위
where n % 2 == 0
// where 은 조건 필터
orderby n descending
// orderby 는 기본 오름차순, 끝에 ascending과 descending 키워드 사용 가능.
select n;
// select 는 결과 출력문(프로퍼티 가능, 무명 형식 가능)
foreach (int n in result)
Console.WriteLine($"짝수 : {n}");
}
}
}
---------------------------------------------------------------------
using System;
using System.Linq;
namespace Join
{
class Profile
{
public string Name { get; set; }
public int Height { get; set; }
}
class Product
{
public string Title { get; set; }
public string Star { get; set; }
}
class MainApp
{
static void Main(string[] args)
{
Profile[] arrProfile =
{
new Profile(){Name="정우성", Height=186},
new Profile(){Name="김태희", Height=158},
new Profile(){Name="고현정", Height=172},
new Profile(){Name="이문세", Height=178},
new Profile(){Name="하하", Height=171}
};
Product[] arrProduct =
{
new Product(){Title="비트", Star="정우성"},
new Product(){Title="CF 다수", Star="김태희"},
new Product(){Title="아이리스", Star="김태희"},
new Product(){Title="모래시계", Star="고현정"},
new Product(){Title="Solo 예찬", Star="이문세"}
};
var listProfile =
from profile in arrProfile
// 조인할 기준이 되는 데이터
join product in arrProduct on profile.Name equals product.Star
// join할 데이터 를 on 같은 것만
select new
// new{} 무명형식을 사용하여 즉시 형식을 만들어 사용 할 수 있음.
{
Name = profile.Name,
Work = product.Title,
Height = profile.Height
};
Console.WriteLine("--- 내부 조인 결과 ---");
foreach (var profile in listProfile)
{
Console.WriteLine("이름:{0}, 작품:{1}, 키:{2}cm",
profile.Name, profile.Work, profile.Height);
}
listProfile =
from profile in arrProfile
join product in arrProduct on profile.Name equals product.Star into ps
외부로 into ps
from sub_product in ps.DefaultIfEmpty(new Product(){Title="그런거 없음"})
// 외부 임시 컬렉션으로 저장하고 .DefaultIfEmpty(new Product(){Title="그런거 없음"})
// 처럼, 새로운 객체를 생성하여 빈 값에 할당. 외부 조인
select new
{
Name = profile.Name,
Work = sub_product.Title,
Height = profile.Height
};
Console.WriteLine();
Console.WriteLine("--- 외부 조인 결과 ---");
foreach (var profile in listProfile)
{
Console.WriteLine("이름:{0}, 작품:{1}, 키:{2}cm",
profile.Name, profile.Work, profile.Height);
}
}
}
}
view raw MainApp.cs hosted with ❤ by GitHub
반응형