Microsoft MVP성태의 닷넷 이야기
.NET Framework: 548. Linq는 결국 메서드 호출! [링크 복사], [링크+제목 복사],
조회: 22018
글쓴 사람
정성태 (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]

... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13339정성태5/6/202313312닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/202311846닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/202312871Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/202312411.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/202313334.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/202312335Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/202310823Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/202311126Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/202310766오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/202311324Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/202311531Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/202311345VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/202311549VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/202314134.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/202312283스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/202312497.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/202312195개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/202313718VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/202311632개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/202311399개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/202312382개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/202312045개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/202312284오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/202310704오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/202311658Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/202312507개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치 [1]
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...