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

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13428정성태10/25/20232961닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233152닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233322스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233140닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233115스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233268닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233313닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235457스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233148스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233840닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233396닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233186오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233677닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233444디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233641닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236917닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233411Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234926닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233783닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233762Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233515닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233474VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233919닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233427오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233262오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233326닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...