다음을 통해 공유


제네릭 Field 및 SetField 메서드(LINQ to DataSet)

LINQ to DataSet은 열 값에 액세스할 수 있도록 확장명 메서드인 Field 메서드 및 SetField 메서드를 DataRow 클래스에 제공합니다. 개발자는 이러한 메서드를 사용하여 열 값에 쉽게 액세스할 수 있으며, 특히 null 값과 관련된 작업을 쉽게 수행할 수 있습니다. DataSetDBNull.Value를 사용하여 Null 값을 나타내는 반면, LINQ는 NullableNullable<T> 형식을 사용합니다. DataRow의 기존 열 접근자를 사용하려면 반환 개체를 적절한 형식으로 캐스팅해야 합니다. 반환된 DataRow가 암시적으로 다른 형식으로 캐스팅되면 DBNull.Value이 throw되므로 InvalidCastException의 특정 필드가 null일 가능성이 있는 경우 명시적으로 null 값을 확인해야 합니다. 다음 예제에서 DataRow.IsNull 메서드를 사용하여 null 값을 확인하지 않으면 인덱서에서 DBNull.Value를 반환하면서 String으로 캐스팅할 때 예외가 throw됩니다.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable products = ds.Tables["Product"];

var query =
    from product in products.AsEnumerable()
    where !product.IsNull("Color") &&
        (string)product["Color"] == "Red"
    select new
    {
        Name = product["Name"],
        ProductNumber = product["ProductNumber"],
        ListPrice = product["ListPrice"]
    };

foreach (var product in query)
{
    Console.WriteLine("Name: {0}", product.Name);
    Console.WriteLine("Product number: {0}", product.ProductNumber);
    Console.WriteLine("List price: ${0}", product.ListPrice);
    Console.WriteLine("");
}
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

Dim products As DataTable = ds.Tables("Product")

Dim query = _
    From product In products.AsEnumerable() _
    Where product!Color IsNot DBNull.Value AndAlso product!Color = "Red" _
    Select New With _
       { _
           .Name = product!Name, _
           .ProductNumber = product!ProductNumber, _
           .ListPrice = product!ListPrice _
       }

For Each product In query
    Console.WriteLine("Name: " & product.Name)
    Console.WriteLine("Product number: " & product.ProductNumber)
    Console.WriteLine("List price: $" & product.ListPrice & vbNewLine)
Next

Field 메서드는 DataRow의 열 값에 대한 액세스를 제공하고 SetFieldDataRow의 열 값을 설정합니다. 이전 예제에서와 마찬가지로, Field 메서드와 SetField 메서드 모두 nullable 값 형식을 처리하므로, 명시적으로 null 값을 검사하지 않아도 됩니다. 또한 두 메서드 모두 제네릭 메서드이므로 반환 형식을 캐스팅하지 않아도 됩니다.

다음 예제에서는 Field 메서드를 사용합니다.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable products = ds.Tables["Product"];

var query =
    from product in products.AsEnumerable()
    where product.Field<string>("Color") == "Red"
    select new
    {
        Name = product.Field<string>("Name"),
        ProductNumber = product.Field<string>("ProductNumber"),
        ListPrice = product.Field<Decimal>("ListPrice")
    };

foreach (var product in query)
{
    Console.WriteLine("Name: {0}", product.Name);
    Console.WriteLine("Product number: {0}", product.ProductNumber);
    Console.WriteLine("List price: ${0}", product.ListPrice);
    Console.WriteLine("");
}
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

Dim products As DataTable = ds.Tables("Product")

Dim query = _
    From product In products.AsEnumerable() _
    Where product.Field(Of String)("Color") = "Red" _
    Select New With _
       { _
           .Name = product.Field(Of String)("Name"), _
           .ProductNumber = product.Field(Of String)("ProductNumber"), _
           .ListPrice = product.Field(Of Decimal)("ListPrice") _
       }

For Each product In query
    Console.WriteLine("Name: " & product.Name)
    Console.WriteLine("Product number: " & product.ProductNumber)
    Console.WriteLine("List price: $ " & product.ListPrice & vbNewLine)
Next

T 메서드 및 Field 메서드의 제네릭 매개 변수 SetField에 지정된 데이터 형식은 내부 값의 형식과 일치해야 합니다. 그렇지 않으면 InvalidCastException 예외가 throw됩니다. 지정된 열 이름도 DataSet의 열 이름과 일치해야 하며, 그렇지 않으면 ArgumentException이 throw됩니다. 두 경우 모두 쿼리가 실행되는 런타임에 데이터 열거형에서 예외가 throw됩니다.

SetField 메서드 자체에서는 형식 변환이 수행되지 않습니다. 그러나 이는 형식 변환이 발생하지 않는다는 의미는 아닙니다. SetField 메서드는 DataRow 클래스의 ADO.NET 동작을 노출합니다. DataRow 개체에서 형식 변환을 수행하면 변환된 값은 DataRow 개체에 저장됩니다.

참고 항목