简体   繁体   English

C#如何使用动态列名称从另一个List <>创建列的List <>

[英]c# how to create List<> of columns from another List<> with dynamic column names

Here the scenario: 这里是场景:

  1. I load date from db and got a List <productModel> products - this one have 80 columns... 我从db加载日期,并得到一个List <productModel> products -该List <productModel> products有80列...
  2. and I have DataTable productsColumnsNames where the User can definite witch columns want to see later in DataGrid. 我有DataTable productsColumnsNames ,用户可以在其中定义希望稍后在DataGrid中看到的列。
  3. Everything happens dynamically so here is my problem... for example the User choose col4, col7, col8, col26, col55 (columns name) how I can get the result in new or the List? 一切都是动态发生的,所以这是我的问题...例如,用户选择col4,col7,col8,col26,col55(列名),如何获取new或List中的结果?

I reading a lot about this online I sow couple of different solusions but not one working with my problem... 我在网上阅读了很多有关此问题的信息,因此播种了几种不同的解决方案,但没有一个解决我的问题...
One of solutions is this one (come from other example for for ListView) and of course don´t working with List but will be great is possible to modified for my code 解决方案之一就是这个(来自ListView的其他示例),当然不使用List,但是可以为我的代码修改很棒

var columnNames = new List<string> { colName1, colName3, colName3 };

var columnsToDelete = productsa.Where(c => !columnNames.Contains(c.Name));

foreach (var column in columnsToDelete)
{
    ResultsLogTab_ListView.Columns.Remove(column);
}

You are filtering the products list using the column names. 您正在使用列名过滤产品列表。 You should be filtering the products list only if you want to exclude certain products. 仅当您要排除某些产品时,才应过滤产品列表。

In this case, you can create a new list with only the required columns and copy from the first list to second for all rows. 在这种情况下,您可以创建仅包含必需列的新列表,然后将所有行从第一个列表复制到第二个列表。 You can also use automapper to map the two lists, but the second list needs to be defined first. 您也可以使用自动映射器来映射两个列表,但是第二个列表需要首先定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM