티스토리 뷰

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace item
{
    internal class App
    {
        public App()
        {
            //저장된 json 파일읽기 (File.ReadAllText)
            string json = File.ReadAllText("./item_data.json"); //데이터 테이블

            //아이템 데이터 객체에 역직렬화하기
            Item[] items = JsonConvert.DeserializeObject<Item[]>(json); //<Item[]>의 json 을 Item[] items에 할당

            //출력해서 확인해보자
            foreach (Item item in items)
            {
                Console.WriteLine("ID:{0}, NAME:{1}, DAMAGE:{2}", item.id, item.name, item.damage);
            }

            //만약 특정 id에 해당하는 ItemData를 찾아보자, 반복문 순회
            Item foundItem= null;
            int seachId = 101;
            foreach(Item item in items)
            {
                if(seachId== item.id)
                {
                    foundItem=item;
                    break;
                }
            }
            if(foundItem!= null)
            {
                Console.WriteLine("아이템이 있습니다.");
                Console.WriteLine("{0},{1},{2}",foundItem.id,foundItem.name,foundItem.damage);
            }
            else
            {
                Console.WriteLine("{0}을 찾지못했습니다",seachId);
            }    

        }
    }
}

#배열에서 연습해보자

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace item
{
    internal class App
    {
        public App()
        {
            //파일 읽기
            string json = File.ReadAllText("./item_data.json");
            //아이템 데이터 객체에 역직렬화
            Item[] items = JsonConvert.DeserializeObject<Item[]>(json);
            //출력으로 확인
            foreach(Item item in items)
            {
                Console.WriteLine("ID:{0}, NAME:{1}, DAMAGE:{2}",item.id,item.name,item.damage);
            }

            //만약 id로 아이템을 찾고싶다면 ? foreach문으로 순회해보자
            Item foundItem = null;
            int searchId = 103;
            foreach(Item item in items)
            {
                if(searchId== item.id)
                {
                    foundItem = item;
                    break;
                }
            }
            if(foundItem != null)
            {
                Console.WriteLine("아이템을 찾음 ID:{0}, NAME:{1}, DAMAGE:{2}",foundItem.id,foundItem.name,foundItem.damage);
            }
            else
            {
                Console.WriteLine("아이템이없음");
            }

        }
    }
}

#사전으로 접근한다면?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace item
{
    internal class App
    {
        public App()
        {
            //파일 읽기
            string json = File.ReadAllText("./item_data.json");
            //아이템 데이터 객체에 역직렬화
            Item[] items = JsonConvert.DeserializeObject<Item[]>(json);

            //사전을 사용하면 key로 찾기 가능
            //먼저 배열에 모든 요소를 사전에 넣어야한다
            //컬랙션은 사용 전 반드시 인스턴스 화
            Dictionary<int, Item> dicItem = new Dictionary<int, Item>(); //key ->int(id) , value->Item의 필드로 사용
            //사전 dicItem에 모두 옴겨 담기
            foreach (Item item in items) 
            {
                dicItem.Add(item.id, item);
            }

            //사전을 순회하며 모든 요소 확인해보기
            foreach(KeyValuePair<int,Item> pair in dicItem)
            {
                int id=pair.Key; //key에 id를
                Item item = pair.Value; //value에 item을...
                Console.WriteLine("ID:{0}, NAME:{1}, DAMAGE:{2}",id,item.name,item.damage);
            }

            //Id로 아이템 name과 damage출력
            int searchId = 102;
            if(dicItem.ContainsKey(searchId)) //만약 찾고있는 key 값 searchId가 있다면?
            {
                Item foundItem = dicItem[searchId]; //dicItem[key값]의 value를 foundItem에 할당
                Console.WriteLine("ID:{0}, NAME:{1}, DAMAGE:{2}",foundItem.id,foundItem.name,foundItem.damage);
            }
        }
    }
}

'C# > 복습' 카테고리의 다른 글

컬렉션(Array List), List<T>  (0) 2023.01.21
프로퍼티  (0) 2023.01.21
직렬화, 역직렬화 연습  (0) 2023.01.15
Linq  (0) 2023.01.15
대리자  (0) 2023.01.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함