230824_ Array & Linq

Minsang Kim·2023년 8월 24일
0

TIL

목록 보기
13/41

오늘부터 내배캠에서 코테 대비를 한다. 그 동안에 나는 파이썬으로 코테를 준비해왔기 때문에 파이썬이 훨-씬 편하지만, 공부되지 않을까 하는 생각에 한 번 C#으로도 도전해보자.
그리고 엄청난 기능을 찾아버림. 바로 코테 문제를 풀면 자동으로 깃허브로 업데이트 되는거임. 이걸로 하루 3문제는 풀어보도록 노력해보자 일기처럼. 가보자잇 !


System.Array

매번 배열을 선언하고 하기 귀찮아졌다. 파이썬처럼 뭔가 메소드가 있지 않나 하고 찾아봤더니 역시나 있었다.

메소드사용
Sort(array)정렬
Foreach(array, Action)배열 내 모든 요소에 Action 수행
BinarySearch(array, value)value 이진 탐색
IndexOf(array, value)value 선형 탐색
TrueForAll(array, Predicate)배열 내 모든 요소의 Predicate 조건 확인
FindIndex(array, Predicate)Predicate 조건의 첫 번째 인덱스
Resize(ref array, int)배열 크기 재조정
Clear(array, index, length)index 부터 length만큼 배열 값 초기화
using System;
static bool CheckPassed(int score)
{
    return score >= 60;
}

static void Print(int value)
{
    Console.Write(value + " ");
}

static void Main()
{
    int[] scores = { 55, 80, 90, 65, 77 };

    Array.Sort(scores);
    
    Array.ForEach(scores, new Action<int>(Print));

    Console.WriteLine($"Number of Dimensions : {scores.Rank}");

    Console.WriteLine($"Binaray Search : 80 is at {Array.BinarySearch(scores, 80)}");

    Console.WriteLine($"Linear Search : 90 is at {Array.IndexOf(scores, 90)}");

    Console.WriteLine($"Everyone passed ? : {Array.TrueForAll(scores, CheckPassed)}");

    Console.WriteLine($"Who's Failed ? : {Array.FindIndex(scores, delegate (int score) { return score < 60; })}");

    Array.Resize(ref scores, 10);

    Array.Clear(scores, 2, 1);
}

알아두고 유용하게 써먹자.

System.Linq

링크 : Language INtegrated Query. (젤다의 전설 아님)
C#에서 컬렉션 형태의 데이터를 가공할 때 유용한 메서드가 가득.
긴 말 말고 바로 확인해보자

메소드사용
Sum()
Count()갯수 (= Length)
Average()평균 값
Max()최댓값
Min()최솟값

람다 식으로 조건 처리

내가 볼 때 링크에서 제일 맛있는 건 이 람다식이다.
여러가지 람다식을 매개변수로 받는 메소드를 araboza.

  • Where() : IEnumerable 형태의 데이터 가져오기
    IEnumerable<int> newNumbers = numbers.Where(number => number > 3);
  • ToList() : IEnumerable를 List로 변환하기
    List<int> newNumbers = numbers.Where(number => number > 3).ToList();

  • All() : 모든 조건을 만족하면 true, else false
    if (checkList.All(c => c))

  • Any() : 하나라도 만족하면 true, else false
    if (checkList.Any(c => c))

  • OrderBy() : 데이터 정렬 - 오름차순

  • OrderByDescending() : 데이터 정렬 - 내림차순
    IEnumerable<int> newNumbers = numList.OrderBy(num => num);

  • Contains() : 특정 문자열을 포함하는가
    IEnumerable<string> newColors = colors.Where(c => c.ToLower().Contains('e'));
    대문자 소분자를 구분하기 때문에 .ToUpper() 또는 .ToLower() 메소드를 사용해 한쪽으로 바꿔 검색해보자.

  • Single() : 단 하나만 가져오기

  • SingleOrDefault() : 단 하나만 가져오기 없으면 null

  • First() : 처음 꺼 하나만 가져오기

  • FirstOrDefault() : 처음 꺼 하나만 가져오기 없으면 null
    int num = numbers.First(n => n == 1)

  • 쿼리 구문 Query Syntax
    IEnumerable<int> oddNumbers = from n in numbers where n % 2 == 0 select n;


세줄 요약

  • C# 코테 맛보기
  • Linq는 파이썬에는 그냥 있는디
  • 깃허브에 일기처럼 코테 올리기
profile
게임만 하다가 개발자로

0개의 댓글