프로젝션은 데이터 집합을 필터링하고 모양과 형식을 변경하는 프로세스입니다. 대부분의 쿼리 식은 프로젝션을 수행합니다. 이 섹션에 있는 대부분의 쿼리 식은 IEnumerable<T>의 XElement(을)를 평가하지만 다른 형식의 컬렉션을 만들 수 있습니다. 이 문서에서는 이를 수행하는 방법을 보여 줍니다.
예: 새 형식을 정의하고 해당 형식의 IEnumerable을 만드는 쿼리 만들기
다음 예제에서는 새 형식 Customer
(을)를 정의하고 쿼리 식은 Select
절의 새 Customer
개체를 인스턴스화합니다. 이에 따라 쿼리 식의 형식이 IEnumerable<T>의 Customer
이 됩니다. 이 예제에서는 XML 문서 샘플 XML 파일인 고객 및 주문을 사용합니다.
public class Customer
{
private string customerID;
public string CustomerID{ get{return customerID;} set{customerID = value;}}
private string companyName;
public string CompanyName{ get{return companyName;} set{companyName = value;}}
private string contactName;
public string ContactName { get{return contactName;} set{contactName = value;}}
public Customer(string customerID, string companyName, string contactName)
{
CustomerID = customerID;
CompanyName = companyName;
ContactName = contactName;
}
public override string ToString()
{
return $"{this.customerID}:{this.companyName}:{this.contactName}";
}
}
class Program
{
static void Main(string[] args)
{
XElement custOrd = XElement.Load("CustomersOrders.xml");
IEnumerable<Customer> custList =
from el in custOrd.Element("Customers").Elements("Customer")
select new Customer(
(string)el.Attribute("CustomerID"),
(string)el.Element("CompanyName"),
(string)el.Element("ContactName")
);
foreach (Customer cust in custList)
Console.WriteLine(cust);
}
}
Public Class Customer
Private customerIDValue As String
Public Property CustomerID() As String
Get
Return customerIDValue
End Get
Set(ByVal value As String)
customerIDValue = value
End Set
End Property
Private companyNameValue As String
Public Property CompanyName() As String
Get
Return companyNameValue
End Get
Set(ByVal value As String)
companyNameValue = value
End Set
End Property
Private contactNameValue As String
Public Property ContactName() As String
Get
Return contactNameValue
End Get
Set(ByVal value As String)
contactNameValue = value
End Set
End Property
Public Sub New(ByVal customerID As String, _
ByVal companyName As String, _
ByVal contactName As String)
CustomerIDValue = customerID
CompanyNameValue = companyName
ContactNameValue = contactName
End Sub
Public Overrides Function ToString() As String
Return String.Format("{0}:{1}:{2}", Me.CustomerID, Me.CompanyName, Me.ContactName)
End Function
End Class
Sub Main()
Dim custOrd As XElement = XElement.Load("CustomersOrders.xml")
Dim custList As IEnumerable(Of Customer) = _
From el In custOrd.<Customers>.<Customer> _
Select New Customer( _
el.@<CustomerID>, _
el.<CompanyName>.Value, _
el.<ContactName>.Value _
)
For Each cust In custList
Console.WriteLine(cust)
Next
End Sub
이 예제는 다음과 같은 출력을 생성합니다.
GREAL:Great Lakes Food Market:Howard Snyder
HUNGC:Hungry Coyote Import Store:Yoshi Latimer
LAZYK:Lazy K Kountry Store:John Steel
LETSS:Let's Stop N Shop:Jaime Yorres
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET