Microsoft MVP성태의 닷넷 이야기
.NET Framework: 548. Linq는 결국 메서드 호출! [링크 복사], [링크+제목 복사],
조회: 22037
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

Linq는 결국 메서드 호출!

다음과 같은 질문이 있군요. ^^

2개의 DataTable Join 결과 전체 컬럼을 DataTable 로 리턴하기
; https://www.sysnet.pe.kr/3/0/3701

정리해 보면, 다음과 같은 식으로 DataTable이 마련되어 있을 때,

DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(string));
dtResult.Columns.Add("name", typeof(string));
dtResult.Columns.Add("stock", typeof(int));
dtResult.Columns.Add("ID2", typeof(string));
dtResult.Columns.Add("name2", typeof(string));
dtResult.Columns.Add("stock2", typeof(int));

DataTable table1 = new DataTable();

table1.Columns.Add("ID", typeof(string));
table1.Columns.Add("name", typeof(string));
table1.Columns.Add("stock", typeof(int));

table1.LoadDataRow(new object[] { "5", "test1", 500 }, true);
table1.LoadDataRow(new object[] { "6", "test2", 600 }, true);
table1.LoadDataRow(new object[] { "7", "test3", 700 }, true);

DataTable table2 = new DataTable();

table2.Columns.Add("ID2", typeof(string));
table2.Columns.Add("name2", typeof(string));
table2.Columns.Add("stock2", typeof(int));

table2.LoadDataRow(new object[] { "5", "test12", 510 }, true);
table2.LoadDataRow(new object[] { "6", "test22", 610 }, true);
table2.LoadDataRow(new object[] { "7", "test32", 710 }, true);

한번의 LINQ 쿼리로 tabl1과 table2의 join 결과를 dtResult에 담고 싶다는 것입니다. 물론, 질문하신 분의 2가지 Linq 쿼리는 그런 것을 못한다는 것이고, 제가 답변을 한 StackOverflow의 글에서는 그에 대한 해결책이 표현되어 있습니다.

간단합니다. 다음과 같이 해주면 해결됩니다.

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID2")
             select dtResult.LoadDataRow(dataRows1.ItemArray.Concat(dataRows2.ItemArray).ToArray<object>(), false);

DataTable my = result.CopyToDataTable();

실제로 위의 코드를 실행해서 출력해 보면,

DataSet ds = new DataSet("test");
ds.Tables.Add(my);

Console.WriteLine(ds.GetXml());

다음과 같은 결과를 얻습니다.

<test>
  <Table1>
    <ID>5</ID>
    <name>test1</name>
    <stock>500</stock>
    <ID2>5</ID2>
    <name2>test12</name2>
    <stock2>510</stock2>
  </Table1>
  <Table1>
    <ID>6</ID>
    <name>test2</name>
    <stock>600</stock>
    <ID2>6</ID2>
    <name2>test22</name2>
    <stock2>610</stock2>
  </Table1>
  <Table1>
    <ID>7</ID>
    <name>test3</name>
    <stock>700</stock>
    <ID2>7</ID2>
    <name2>test32</name2>
    <stock2>710</stock2>
  </Table1>
</test>

그런데, 여기서 제가 하고 싶은 말은... Linq는 단순한 메서드 호출의 나열에 불과하다는 것입니다. 일례로, 위의 Linq 쿼리에서 select 문을 개선해 볼까요?

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID2")
             select dtResult.LoadDataRow(dataRows1.ItemArray.Concat(dataRows2.ItemArray).ToArray<object>(), false);

가령, 다음과 같이 메서드로 바꿔줄 수 있습니다.

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID2")
             select MergeRows(dtResult, dataRows1, dataRows2);


private static DataRow MergeRows(DataTable table, DataRow dataRows1, DataRow dataRows2)
{
    List<object> list = new List<object>();

    list.AddRange(dataRows1.ItemArray);
    list.AddRange(dataRows2.ItemArray);

    return table.LoadDataRow(list.ToArray(), false);
}

또는, table 정의를 바꾸고 그에 맞게 데이터를 채우는 것도 가능합니다. 가령, 다음은 ID2 컬럼을 제외하고 있습니다.

DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(string));
dtResult.Columns.Add("name", typeof(string));
dtResult.Columns.Add("stock", typeof(int));
dtResult.Columns.Add("name2", typeof(string));
dtResult.Columns.Add("stock2", typeof(int));

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID2")
             select MergeRows2(dtResult, dataRows1, dataRows2);

private static DataRow MergeRows2(DataTable table, DataRow dataRows1, DataRow dataRows2)
{
    List<object> list = new List<object>();

    list.AddRange(dataRows1.ItemArray);
    list.AddRange(dataRows2.ItemArray.Skip(1));

    return table.LoadDataRow(list.ToArray(), false);
}

/*
<test>
  <Table1>
    <ID>5</ID>
    <name>test1</name>
    <stock>500</stock>
    <name2>test12</name2>
    <stock2>510</stock2>
  </Table1>
  <Table1>
    <ID>6</ID>
    <name>test2</name>
    <stock>600</stock>
    <name2>test22</name2>
    <stock2>610</stock2>
  </Table1>
  <Table1>
    <ID>7</ID>
    <name>test3</name>
    <stock>700</stock>
    <name2>test32</name2>
    <stock2>710</stock2>
  </Table1>
</test>
*/

이 정도면... 대충 감이 오시죠? ^^

(첨부 파일은 위의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/20/2016]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2016-02-22 02시55분
[강준] 답변 감사합니다.
그런데 제가 원했던건 dtResult 가 없는상태에서 결과를 도출할수 없는가 였습니다.^^
A 테이블과 B 테이블의 컬럼을 알 수 없고 키만 같고 결과로는 키와 함께 다른 컬럼들도 같이해서
결과를 보고 싶었던것입니다.^^
일단 이런 방법도 있는 걸 알게 되었네요
[guest]
2016-02-22 03시03분
제가 MergeRows2를 작성한 것은 그에 대한 다양한 요구 사양을 만족시킬 수 있다는 것을 알려드린 것입니다. dtResult를 굳이 안 받아도 전달받은 DataRow 2개의 컬럼 값을 런타임시에 알아내서 dtResult를 임의로 구성해 처리할 수 있습니다. (물론, 매번 구성하면 성능 손실이 심각하니 static 유형의 캐시 관리를 추가해야 할 것입니다.)

그러니까, 이 글에서는 Linq를 제약된 환경으로 인식하지 말고 예전의 메서드 호출과 동일하게 보라는 것입니다.

즉 Linq를 생각하지 말고, 2개의 DataRow가 조합된 데이터들을 어떻게 DataTable에 넣을 수 있을까요?.... 와 같은 문제입니다.
정성태
2016-02-22 04시10분
[강준] 네 말씀하신데로 런타임시에는 알수가 있어서 그렇게 처리를 하긴 했습니다.^^
암튼 linq 내에서 메서드 호출이 가능하다는걸 알았네요
(람다식을 이용하면 먼가 제약이 있던데..)
답변 감사합니다~

[guest]

... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11274정성태8/22/201719321.NET Framework: 674. Thread 타입의 Suspend/Resume/Join 사용 관련 예외 처리
11273정성태8/22/201721624오류 유형: 415. 윈도우 업데이트 에러 Error 0x80070643
11272정성태8/21/201724746VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201719170VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201730620.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201721423디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201721000디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201725078.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201724876.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201753125기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
11264정성태8/9/201724011오류 유형: 414. UWP app을 signtool.exe로 서명 시 0x8007000b 오류 발생
11263정성태8/9/201719481오류 유형: 413. The C# project "..." is targeting ".NETFramework, Version=v4.0", which is not installed on this machine. [3]
11262정성태8/5/201718203오류 유형: 412. windbg - SOS does not support the current target architecture. [3]
11261정성태8/4/201720784디버깅 기술: 91. windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법
11260정성태8/3/201718872.NET Framework: 670. C# - 실행 파일로부터 공개키를 추출하는 방법
11259정성태8/2/201718128.NET Framework: 669. 지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법
11258정성태8/1/201718894.NET Framework: 668. 지연 서명된 DLL과 서명된 DLL의 차이점파일 다운로드1
11257정성태7/31/201719129.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201720587디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201723163디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201719483개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201719760Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201718415오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201717074디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201720663디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718458오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...