查找并替换多个值对

时间:2016-01-19 12:36:17

标签: c# asp.net .net

如果之前有人问过,我只能看到其他语言的解决方案,并且不知道正确的c#术语用于描述问题。

我有List<Person>,其中每个Person对象都有SiteDepartment字符串属性。

由于不同ERP系统的命名约定不同,我需要阅读每个人的网站/部门的价值,并根据在查找表中找到的匹配项,替换它们:

enter image description here

目前我可以像这样手动编码:

foreach (Person p in pi.People)
{
    if (p.Site == "New York" && p.Department == "HR")
    {
        p.Department = "Human Resources";
    }
    else if (p.Site == "Seattle" && p.Department == "Production")
    {
        p.Site = "Redmond";
        p.Department = "Prod Ax-Rdm";
    }
    // .... removed for brevity
}

我想知道是否有更好/更聪明的方法来实现相同的目标呢?查找表中大约有20行,列表中大约有700个人。

我的初衷是使用DataTable(4列,“旧”列上有索引)。

如果有人对更好的方法提出了很好的建议,我很乐意去RTFM。

1 个答案:

答案 0 :(得分:3)

创建一个查找类:

public class MyLookup
{
    public string OldSite { get; set; }
    public string OldDepartment { get; set; }
    public string NewSite { get; set; }
    public string NewDepartment { get; set; }
}

创建查找表:

var myLookups = new MyLookup[20];

myLookups[0] =
    new MyLookup
    {
        OldSite = "foo",
        OldDepartment = "bar",
        NewSite = "baz",
        NewDepartment = "qux"
    };

[…]

迭代记录,查找新值并更新记录:

foreach (var person in pi.People)
{
    var myLookup =
        myLookups
        .SingleOrDefault(a =>
            a.OldSite == person.Site
            && a.OldDepartment == person.Deparment);

    if (myLookup == null)
    {
        // Handle a missing lookup accordingly.
        throw new Exception("Where is my lookup?!");
    }

    person.Site = myLookup.NewSite;
    person.Deparment = myLookup.NewDepartment;
}