🌈 .NET MVC
임시 리스트 만들기(temporary list)
James Wetzel
2024. 6. 18. 14:33
728x90
반응형
임시 리스트 만들기(temporary list)
코드를 작성하다 보면 클래스(class) 형식이 아닌 임시(temporary) 형식를 가진 List가 필요할때가 있다.
상황적 예를 든다면, 다른 코드에서는 참조되지 않고
한번 사용 후 폐기 되는 List 같은 경우 클래스(class) 형식 만들 필요가 없다.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a temporary list with anonymous types
var tempList = new List<object>
{
new { Name = "John", Age = 30 },
new { Name = "Jane", Age = 25 }
};
// Iterating through the list
foreach (var person in tempList)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
비고
임시(temporary) 형식를 가진 List에서 특정 값 식별하기
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a list of objects
List<object> tempList = new List<object>
{
new { Name = "John", Age = 30 },
new { Name = "Jane", Age = 25 },
new { Name = "Joe", Age = 35 }
};
// Using the Find method to find the first object where Name is "Jane"
var result = tempList.Find(item =>
{
// Cast item to anonymous type
var person = item as dynamic;
return person.Name == "Jane";
});
if (result != null)
{
// Cast result to anonymous type to access properties
var person = result as dynamic;
Console.WriteLine($"Found: Name = {person.Name}, Age = {person.Age}");
}
else
{
Console.WriteLine("No matching item found.");
}
}
}
728x90
반응형