통합검색
· 마을서비스란?  · 포럼마을  · 일반마을  · 테마마을  · 마을랭킹  · 활동왕
· 덱스퍼트란?  · TECBOX   · PRSBOX   · 이용안내  
· DEXT제품군  · 솔루션베이  · S/W & ESD 컴포넌트
· 프로그램베이
· LiveSeminar  · LiveConference
데브피아 C# 포럼 마을에 오신 것을 환영합니다.
  마을등급 C#   이 마을은 포럼마을 입니다이 마을은 자유가입제 마을 입니다 마을소개 페이지로 이동 전입신청
마을촌장촌장 비사모 주민 12891 since 2006-12-28
우리마을 공지사항
질문&답변
강좌&팁
자유게시판
자료실
앨범
개인게시판
[마을 게시판]
구인/구직 게시판
건의 / 운영 제안
랑데브 게시판
칼럼 게시판
개발자 고충상담
Dev Talk
자유토론방
벼룩시장
재나미 우스개
구인/프로젝트 정보
사람인 채용 게시판
  고객지원 게시판
마이 데브피아
 나의 e-Money 내역
 활동왕 My Page
 스크랩한 게시글보기
 쪽지관리
 주소록관리

 강좌&팁
 DataTable Pivot 테이블 피봇  | WinForm Program 2019-12-02 오후 4:49:47
 windlee5  windlee5님께 메시지 보내기windlee5님을 내 주소록에 추가합니다.windlee5님의 개인게시판 가기 번호: 2079 추천:0  / 읽음:374

소스는 첨부파일에.. VS 2017

 

 https://stackoverflow.com/questions/17971921/how-to-convert-row-to-column-in-linq-and-sql

 
 

 
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using ChartFX.WinForms;
using System.Linq;
using System.Linq.Expressions;
namespace AxisLabels
{
 public partial class Form1 : Form
 {
        ChartFX.WinForms.Chart chart2;
        public Form1()
        {
            InitializeComponent();  
        }
        /// <summary>
        /// Series 설정, Series 의 갯수만큼 설정
        /// </summary>
        /// <param name="oChart"></param>
        private void SetSeries (ChartFX.WinForms.Chart oChart)
        {
            int iCnt = chart2.Series.Count;
            for (int iSeries = 0;iSeries < iCnt; iSeries++)
            {
                SetSeriesProperty(chart2, Gallery.Bar);
            }
        }
        /// <summary>
        /// Series Property 를 설정하는 부분, Series 의 순차로 설정
        /// </summary>
        /// <param name="oChart"></param>
        /// <param name="oGallery"></param>
        /// <param name="sSeriesText"></param>
        /// <param name="oMarkerShape"></param>
        /// <param name="bShowPointLabel"></param>
        /// <param name="oColor"></param>
        private void SetSeriesProperty(ChartFX.WinForms.Chart oChart
                                        , Gallery oGallery, string sSeriesText = null
                                        , MarkerShape oMarkerShape = MarkerShape.None
                                        , bool bShowPointLabel = false
                                        , System.Drawing.Color? oColor = null
                                    )
        {
            int iCnt = oChart.Series.Count;
            for (int ii = 0; ii < iCnt; ii++)
            {
                if (null == oChart.Series[ii].Tag)
                {
                    oChart.Series[ii].Gallery = oGallery;
                    oChart.Series[ii].MarkerShape = oMarkerShape;
                    oChart.Series[ii].PointLabels.Visible = bShowPointLabel;   //chart1.AllSeries.PointLabels.Visible = true;
                    oChart.Series[ii].Color = oColor ?? oChart.Series[ii].Color;
                    oChart.Series[ii].Text = sSeriesText ?? oChart.Series[ii].Text;
                    oChart.Series[ii].Tag = ii.ToString();  // 이 값을 기준으로 셋팅여부 확인
                    break;
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            ReadChartData();
        }
        void ReadChartData()
  {
            chart2 = new Chart();
            chart2.Dock = DockStyle.Fill;
            DataTable dt = (DataTable)Util.dtHandle();
            SetFieldUsage(chart2, dt);
            SetSeries(chart2);
            panel1.Controls.Add(chart2);
        }
        /// <summary>
        /// https://imgur.com/pyeZyM0 처럼 pivot 된 DataTable 의 값을 가지고 Chart 에 Mapping 함
        /// </summary>
        /// <param name="oChart"></param>
        private void SetFieldUsage(ChartFX.WinForms.Chart oChart, DataTable dtFieldUsage)
        {
            oChart.DataSourceSettings.Fields.Add(new FieldMap(dtFieldUsage.Columns[0].ColumnName, FieldUsage.Label));
            int iCnt = dtFieldUsage.Columns.Count;
            for (int i=1; i < iCnt; i++)
            {
                oChart.DataSourceSettings.Fields.Add(new FieldMap(dtFieldUsage.Columns[i].ColumnName, FieldUsage.Value));
            }
            oChart.DataSource = dtFieldUsage;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            ReadChartData();
        }
    }
    public static class Util
    {
        public static DataTable dtHandle()
        {
            DataTable myDataTable = new DataTable();
            myDataTable.Columns.AddRange
            (
                new DataColumn[3]
                {
                        new DataColumn("Product", typeof(string))
                        , new DataColumn("Year", typeof(string))
                        , new DataColumn("Sales", typeof(decimal))
                }
            );
            Random rnd = new Random(int.Parse(System.DateTime.Now.ToString("fff")));
            myDataTable.Rows.Add("JAN", "Product 1", rnd.NextDouble()*3);
            myDataTable.Rows.Add("JAN", "Product 2", rnd.NextDouble()*3);
            myDataTable.Rows.Add("JAN", "Product 3", rnd.NextDouble()*3);
            myDataTable.Rows.Add("FEB", "Product 1", rnd.NextDouble()*3);
            myDataTable.Rows.Add("FEB", "Product 2", rnd.NextDouble()*3);
            myDataTable.Rows.Add("FEB", "Product 3", rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW19", "Product 1",rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW19", "Product 2",rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW19", "Product 3",rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW20", "Product 1",rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW20", "Product 2",rnd.NextDouble()*3);
            myDataTable.Rows.Add("WW20", "Product 3", rnd.NextDouble() * 3);
            myDataTable.Rows.Add("D1", "Product 1", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D1", "Product 2", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D1", "Product 3", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D1", "Product 4", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D1", "Product 5", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D1", "Product 6", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 1", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 2", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 3", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 4", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 5", rnd.NextDouble()*3);
            myDataTable.Rows.Add("D2", "Product 6", rnd.NextDouble()*3);
            var data2 = myDataTable.AsEnumerable().Select(x => new
            {
                Product = x.Field<string>("Product"),
                Year = x.Field<string>("Year"),
                Sales = x.Field<decimal>("Sales"),
            });
            DataTable tableResult = data2.ToPivotTable
            (
                item => item.Year
                , item => item.Product
                , items => items.Any() ? items.Sum(x => x.Sales) : 0
            );
            return tableResult;
        }
        /// <summary>
        /// https://imgur.com/pyeZyM0 처럼 pivot 함
        /// </summary>
        /// <typeparam name="T">Data 원 소스</typeparam>
        /// <typeparam name="TColumn">Pivot 시에 왼쪽 최초의 Column 이 될 컬럼명</typeparam>
        /// <typeparam name="TRow">첫번째 Row 에 순서대로 들어갈 컬럼명</typeparam>
        /// <typeparam name="TData">첫번째 Row 에 순서대로 배치된 컬럼에 해당되는 값이 될 컬럼명</typeparam>
        /// <param name="source"></param>
        /// <param name="columnSelector"></param>
        /// <param name="rowSelector"></param>
        /// <param name="dataSelector"></param>
        /// <returns></returns>
        public static DataTable ToPivotTable<T, TColumn, TRow, TData>(
            this IEnumerable<T> source,
            Func<T, TColumn> columnSelector,
            Expression<Func<T, TRow>> rowSelector,
            Func<IEnumerable<T>, TData> dataSelector)
        {
            DataTable table = new DataTable();
            var rowName = ((MemberExpression)rowSelector.Body).Member.Name;
            table.Columns.Add(new DataColumn(rowName));
            var columns = source.Select(columnSelector).Distinct();
            foreach (var column in columns)
                table.Columns.Add(new DataColumn(column.ToString()));
            var rows = source.GroupBy(rowSelector.Compile())
                             .Select(rowGroup => new {
                                 Key = rowGroup.Key,
                                 Values = columns.GroupJoin(
                                     rowGroup,
                                     c => c,
                                     r => columnSelector(r),
                                     (c, columnGroup) => dataSelector(columnGroup))
                             });
            foreach (var row in rows)
            {
                var dataRow = table.NewRow();
                var items = row.Values.Cast<object>().ToList();
                items.Insert(0, row.Key);
                dataRow.ItemArray = items.ToArray();
                table.Rows.Add(dataRow);
            }
            return table;
        }
    }
}
 
------------------------------



ChartFX7_AxisLabels.zip

해당 소스는 ChartFx 7 정식/데모버젼이 필요함.
 

 

코멘트쓰기
  좋음   놀람   궁금   화남   슬픔   최고   침묵   시무룩   부끄럼   난감
* 코멘트는 500자 이내(띄어쓰기 포함)로 적어주세요.
목록 보기   지금 보고 계시는 글을 회원님의 my Mblog >> 스크랩에 넣어두고 다음에 바로 보실 수 있습니다.  
회사소개  |   개인정보취급방침  |  제휴문의  |   광고문의  |   E-Mail 무단수집거부  |   고객지원  |   이용안내  |   세금계산서
사업자등록번호 안내: 220-81-90008 / 통신판매업신고번호 제 2017-서울구로-0055호 / 대표: 홍영준, 서민호
08390, 서울시 구로구 디지털로32길 30, 1211호 / TEL. 02_6719_6200 / FAX. 02-6499-1910
Copyright ⓒ (주) 데브피아. All rights reserved.