더보기
using System.Security.Cryptography;
namespace Study
{
class Program
{
public enum ClassType
{
Knight,
Archer,
Mage
}
public class Player
{
public ClassType ClassType;
public int Level;
public int Hp;
public int Attack;
public List<int> Items = new List<int>();
}
static List<Player> _players = new List<Player>();
static void Main(string[] args)
{
Random rand = new Random();
for (int i = 0; i < 100; ++i)
{
Player player =
new Player()
{
ClassType = (ClassType)rand.Next(0, 3),
Level = rand.Next(0, 100),
Hp = rand.Next(100, 1000),
Attack = rand.Next(50, 100),
};
for (int j = 0; j < 5; ++j) { player.Items.Add(rand.Next(1, 101)); }
_players.Add(player);
}
//Q. 모든 아이템 목록을 추출
{
var playerItems = from p in _players
from i in p.Items
where i < 30
select new { p, i };
var li = playerItems.ToList();
foreach (var info in li)
{
Console.WriteLine($"{info.i} {info.p.ClassType}");
}
}
//Grouping
{
var playerByLevel = from p in _players
group p by p.Level into g
orderby g.Key
select new { g.Key, players = g };
foreach (var player in playerByLevel)
{
Console.WriteLine($"Group by level: {player.Key}");
foreach(Player p in player.players)
{
Console.WriteLine($"\t\tLEVEL:{p.Level}, HP:{p.Hp}, TYPE:{p.ClassType}");
}
Console.WriteLine();
}
}
//Join
{
List<int> levels = new List<int>() { 1, 5 ,10 };
var playerLevels = from p in _players
join l in levels
on p.Level equals l
select p;
foreach(Player player in playerLevels)
{
Console.WriteLine($"LEVEL:{player.Level}, HP:{player.Hp}, TYPE:{player.ClassType}");
}
}
}
}
}
· 중첩 from
var playerItems = from p in _players
from i in p.Items
where i < 30
select new { p, i };
var li = playerItems.ToList();
foreach (var info in li)
{
Console.WriteLine($"{info.i} {info.p.ClassType}");
}
- from을 중첩하여 사용할 수 있습니다. List<Player>인 _player에 있는 p.Item에 접근하여 사용한 예제입니다.
· grouping
var playerByLevel = from p in _players
group p by p.Level into g
orderby g.Key
select new { g.Key, players = g };
foreach (var player in playerByLevel)
{
Console.WriteLine($"Group by level: {player.Key}");
foreach(Player p in player.players)
{
Console.WriteLine($"\t\tLEVEL:{p.Level}, HP:{p.Hp}, TYPE:{p.ClassType}");
}
Console.WriteLine();
}
- _players에 있는 리스트 중 특정한 요소끼리 그룹을 지어 리턴할 수 있습니다.
· join
List<int> levels = new List<int>() { 1, 5 ,10 };
var playerLevels = from p in _players
join l in levels
on p.Level equals l
select p;
foreach(Player player in playerLevels)
{
Console.WriteLine($"LEVEL:{player.Level}, HP:{player.Hp}, TYPE:{player.ClassType}");
}
- 두개의 리스트에서 공통되는것끼리 조인하여 리턴할 수 있습니다.
'server > web server' 카테고리의 다른 글
[Web] 속성 바인딩 (0) | 2023.02.23 |
---|---|
[Web] List 바인딩 (0) | 2023.02.23 |
[Web] 바인딩 (0) | 2023.02.23 |
[Web] Blazor Server App 프로젝트 시작 (0) | 2023.02.23 |
[C#] LINQ(Language-Integrated Query) 1 (0) | 2023.02.21 |