C#

LINQ Any, All메서드 사용법

지오준 2021. 7. 18. 15:10
반응형

1.LINQ Any메소드는 컬렉션(List, Array, Dictionary)의 요소중에서 조건에 만족하는 데이터가 존재하는지를 확인하는데 사용됩니다.

샘플코드는 80점을 초과하는 국가가 대륙별로 존재하는지가 확인 가능합니다.

class Test
{
	public string GroupName { get; set; }
	public string ContryName { get; set; }
	public int Points { get; set; }
}

static void Main(string[] args)
{
	//GroupBy, OrderBy에 사용될 샘플데이터
	var result = new List<Test>() {
	new Test {GroupName = "Asia", ContryName = "South Korea", Points = 90},
	new Test {GroupName = "Europe", ContryName = "Germany", Points = 80,},
	new Test {GroupName = "North America", ContryName = "UnIted States", Points = 70},
	new Test {GroupName = "Asia", ContryName = "Malaysia", Points = 60},
	new Test {GroupName = "Europe", ContryName = "Spain", Points = 50},
	new Test {GroupName = "Africa", ContryName = "Nigeria", Points = 80},
	new Test {GroupName = "Asia", ContryName = "Singapore", Points = 70},
};

//대륙별로 그룹매칭
var query = result
	.GroupBy(x => x.GroupName)
	.Select(x => new { Key = x.Key, Bool = x.Any(y => y.Points > 80) });

	//그룹매칭 결과 루프
	foreach (var group in query)
	{
		//80점 초과하는 국가가 존재하는 대륙표시
		if (group.Bool)
		{
			Console.WriteLine(" {0} and up to the 80point", group.Key);
		}
		//80점 초과하는 국가가 존재하지 않는 대륙표시
		else
		{
			Console.WriteLine(" {0} and down to the 80point", group.Key);
		}
	}

	Console.ReadKey();
}

결과값

2.LINQ All메소드는 컬렉션(List, Array, Dictionary)의 요소중에서 조건에 전부 만족하는 데이터가 존재하는지를 확인하는데 사용됩니다.

샘플코드는 모든국가가 80점을 초과하는 대륙이 존재하는지가 확인 가능합니다.

class Test
{
	public string GroupName { get; set; }
	public string ContryName { get; set; }
	public int Points { get; set; }
}

static void Main(string[] args)
{
	//GroupBy, OrderBy에 사용될 샘플데이터
	var result = new List<Test>() {
	new Test {GroupName = "Asia", ContryName = "South Korea", Points = 90},
	new Test {GroupName = "Europe", ContryName = "Germany", Points = 80,},
	new Test {GroupName = "North America", ContryName = "UnIted States", Points = 70},
	new Test {GroupName = "Asia", ContryName = "Malaysia", Points = 60},
	new Test {GroupName = "Europe", ContryName = "Spain", Points = 50},
	new Test {GroupName = "Africa", ContryName = "Nigeria", Points = 80},
	new Test {GroupName = "Asia", ContryName = "Singapore", Points = 70},
};

//대륙별로 그룹매칭
var query = result
	.GroupBy(x => x.GroupName)
	.Select(x => new { Key = x.Key, Bool = x.All(y => y.Points > 80) });

	//그룹매칭 결과 루프
	foreach (var group in query)
	{
		//모든 국가가 80점 초과하는 대륙표시
		if (group.Bool)
		{
			Console.WriteLine(" {0} and up to the 80point", group.Key);
		}
		//모든 국가가 80점 초과하지 않는 대륙표시
		else
		{
			Console.WriteLine(" {0} and down to the 80point", group.Key);
		}
	}

	Console.ReadKey();
}

결과값

LinqSample5.zip
0.18MB

반응형