c# - 使用 LINQ 列出(和返回)的列

标签 c# wpf entity-framework-5

我有一个包含列“Col1”、“Col2”、“Col3”等的记录的 SQL 表......所有都是相同的类型(并且是相同的“事物”)

表和这些列之间的关系本质上是一对多的。我可以创建另一个表并给出它们之间的关系,但我有许多不相关的表,它们都包含“Col1”、“Col2”、“Col3”等...,这需要我多次复制表。

我需要一种方法将这些列转换为列表,并将列表元素放回列中。数据的顺序无关紧要。如果“Col1”包含A,“Col2”包含B,则更新后“Col1”包含B,“Col2”包含A是可以的。

我画了一张漂亮的图作为说明

enter image description here

一种非常丑陋的方法,可以将数据放回原处。

int fieldCount = 0;
foreach (string field in MyList)
{
    switch (fieldCount++)
    {
        case 1:
            entityObject.Col1 = field;
            break;
        case 2:
            entityObject.Col2 = field;
            break;
        case 3:
            entityObject.Col3 = field;
            break;
        case 4:
            entityObject.Col4 = field;
            break;
        case 5:
            entityObject.Col5 = field;
            break;
    }

} 

最佳答案

你可以为此使用反射:

//replace object parameter with some base class if possible
public static List<string> GetColumnValues(object item)
{
    return item.GetType().GetProperties()
        .Where(prop => prop.Name.StartsWith("Col") 
            && prop.PropertyType == typeof(string))
        .Select(prop => prop.GetValue(item) as string)
        .ToList();
}

然后你可以再次使用反射来设置它们:

//replace object parameter with some base class if possible
public static void GetColumnValues(object item, List<string> values)
{
    foreach(var pair in item.GetType().GetProperties()
        .Where(prop => prop.Name.StartsWith("Col") 
            && prop.PropertyType == typeof(string))
        .Zip(values, (prop, value) => new{prop,value})
    {
        pair.prop.SetValue(item, pair.value);
    }
}

关于c# - 使用 LINQ 列出(和返回)的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19531023/

相关文章:

entity-framework - EF : How do I call SaveChanges twice inside a transaction?

c# - 项目的加载程序集

c# - 为什么在这种情况下使用 StringComparison.Ordinal 被认为更可取?

WPF - App.xaml 的 Build Action = Page 时在设计时访问资源

entity-framework-5 - 模拟 DbEntityEntry

c# - 加载后如何使用 POCO 和 DbContext 初始化 Entity Framework 中的对象?

c# - 如何在 ASP.NET 中管理应用程序配置?

c# - UI自动化和菜单项

wpf - M-V-VM WPF : Way to maintain Databinding while passing parent object of Databound object into IValueConverter?

wpf - WPF 中的简单 CRUD 应用