お知らせ

現在サイトのリニューアル作業中のため、全体的にページの表示が乱れています。
投稿日:
言語::C#

なぜこんな実装が必要なのかさっぱり不明ですが、必要になって困ったのでメモ。

DataTableを内部結合したList<Dictionary>をLINQで作る

var loc = new DataTable();
var pep = new DataTable();
loc.Columns.Add("ID");
loc.Columns.Add("LOCATION");
loc.Columns.Add("DELETE_FLG");
loc.Rows.Add("100", "US", "0");
loc.Rows.Add("101", "AU", "1");
loc.Rows.Add("102", "JP", "1");
loc.Rows.Add("103", "CH", "1");
loc.Rows.Add("104", "UK", "1");
loc.Rows.Add("105", "RU", "1");

pep.Columns.Add("LOCATION_ID");
pep.Columns.Add("NAME");
pep.Columns.Add("DELETE_FLG");
pep.Rows.Add("100", "TAKANA", "0");
pep.Rows.Add("101", "YAKATA", "1");
pep.Rows.Add("100", "WADA", "1");
pep.Rows.Add("101", "SHINODA", "1");
pep.Rows.Add("100", "HARUKA", "1");
pep.Rows.Add("105", "SAIONJI", "0");


var result = (
    from l in loc.AsEnumerable()
    join p in pep.AsEnumerable()
    on new {
        a = l.Field<string>("ID"),
        b = l.Field<string>("DELETE_FLG")
    } equals new {
        a = p.Field<string>("LOCATION_ID"),
        b = p.Field<string>("DELETE_FLG")
    }
    select new Dictionary<string, string> {
        {
            "LOCATION_ID",
            l.Field<string>("ID")
        },
        {
            "NAME",
            p.Field<string>("NAME")
        }
    }
).ToList();

List<Dictionary>DataTableを外部結合してList<Dictionary>を操作する

var location = new List<Dictionary<string, string>>();
var fruits = new DataTable();

location.Add(
    new Dictionary<string, string> {
        {
            "ID",
            "001"
        },
        {
            "NAME",
            "Hokkaido"
        }
    }
);
location.Add(
    new Dictionary<string, string> {
        {
            "ID",
            "002"
        },
        {
            "NAME",
            "Aomori"
        }
    }
);
location.Add(
    new Dictionary<string, string> {
        {
            "ID",
            "003"
        },
        {
            "NAME",
            "Iwate"
        }
    }
);

fruits.Columns.Add("LOCATION_ID");
fruits.Columns.Add("NAME");
fruits.Columns.Add("FRUITS_FLG");
fruits.Rows.Add("001", "ikura", "1");
fruits.Rows.Add("001", "uni", "1");
fruits.Rows.Add("002", "ringo", "0");

// dummyは処置待ち用のダミー。locationの操作が目的
var dummy = location
    .Join(
        fruits.AsEnumerable()
        , loc => loc["ID"]
        , fruit => fruit.Field<string>("LOCATION_ID")
        , (loc, fruit) => new { lo = loc, fru = fruit }
    )
    .Select(
        joined => {
            joined.lo["FRUITS_NAME"] = joined.fru.Field<string>("NAME");
            joined.lo["FRUITS_FLG"] = joined.fru.Field<string>("FRUITS_FLG");
            return new Dictionary<string, string>();
        }
    )
    .ToList();