public enum ClassType
{
Knight,
Archer,
Mage,
}
public class Player
{
public ClassType ClassType { get; set; }
public int Level { get; set; }
public int Hp { get; set; }
public int Attack { get; set; }
public List<int> items { get; set; }
}
class Program
{
static List<Player> _players = new List<Player>();
static void Main(string[] args)
{
Random rand = new Random();
for(int i = 0; i < 100; i++)
{
ClassType type = ClassType.Knight;
switch(rand.Next(0, 3))
{
case 0:
type = ClassType.Knight;
break;
case 1:
type = ClassType.Archer;
break;
case 2:
type = ClassType.Mage;
break;
}
Player player = new Player()
{
ClassType = type,
Level = rand.Next(1, 100),
Hp = rand.Next(100, 1000),
Attack = rand.Next(5, 50)
};
_players.Add(player);
}
// 레벨이 50이상인 Knight만 뽑아
// 높은순으로 정렬해보자
List<Player> players = GetHighLevelKnights();
}
// 아래처럼 구현이 가능하지만 LINQ로도 구현이 가능하다
static public List<Player> GetHighLevelKnights()
{
List<Player> players = new List<Player>();
foreash(Player player in _players)
{
if(player.ClassType != ClassType.Knight)
continue;
if(player.Level < 50)
continue;
players.Add(player);
}
players.Sort((lhs, rhs) => { return lhs.Level - rhs.Level; });
return players;
}
}
var players =
from p in _players
where p.ClassType == ClassType.Knight && p.Level >= 50
orderby p.Level ascending
select p;
// 훨씬 직관적이고 간단하게 구현이 가능하다
중첩 from 사용해보기
var playersItem =
from p in _players
from i in p.items
where i < 30
select new {p ,i};
var li = platerItems.ToList();
그룹핑
// 같은 레벨별로 묶어보자
var playersByLevel =
from p in _players
group p by p.Level into g
orderby g.Key
select new { g.Key, Players = g };
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;
LINQ 표준 연산자
var players =
from p in _players
where p.ClassType == ClassType.Knight && p.Level >= 50
orderby p.Level ascending
select p;
// 위와 동일한 문법이다
var players2 = _players
.Where(p => p.ClassType == ClassType.Knight && p.Level >= 50)
.OrderBy(p => p.Level)
.Select(p => p);
어떤걸 사용해도 무방하다