简体   繁体   中英

Get value from column using a column name string c#

I have 2 lists..

The first contains rows with mapping values inlcuding column name, xcord, ycord

The second contains the data I need to map..

I need to get the value in each row using the column name from the first row..

for example

List<SheetMappings> smaps = new List<SheetMappings>();

foreach(maplist m in mlist)
{
  SheetMappings newMap = new SheetMappings();

  foreach(vallist v in vlist)
  {
    newMap.Value = v.{m.ColumnName};

    newMap.xCord = m.xCord;

    newMap.yCord = m.yCord;
  }

  smaps.Add(newMap);
}

Any assitance appreciated

Cheers

Graham

EDIT:

List<SpreadMappings> spreadMapping = new List<SpreadMappings>(); 
foreach (var m in mappings) 
{ 
    foreach (var v in hvalues) 
    { 
        SpreadMappings map = new SpreadMappings(); 
        switch (m.ColumnName) 
        { 
            case “DocHeading”: 
                map.ColumnX = m.ColumnX; 
                map.ColumnY = m.ColumnY; 
                map.ColumnValue = v.DocHeading; 
                map.ColumnName = m.ColumnName; 
                map.ColumnId = v.Id; 
                map.ColumnSheetName = sheetName; spreadMapping.Add(map); 
            break;

If I understand what you're trying to do, you'll need to use reflection to get the value of the property represented by m.ColumnName:

var smaps = new List<SheetMappings>(); 

foreach(maplist m in mlist) 
{
    var pi = typeof(vallist).GetProperty(m.ColumnName);

    var newMap = new SheetMappings(); 

    foreach(vallist v in vlist) 
    {
        newMap.Value = pi.GetValue(v, null); 
        newMap.xCord = m.xCord; 
        newMap.yCord = m.yCord; 
    } 
    smaps.Add(newMap); 
} 

So that's using reflection to get a reference to the PropertyInfo for the property represented by m.ColumnName , then calling PropertyInfo.GetValue to get the value of that property from v.

Well I think the "newMap.Value = v.{m.ColumnName}" part would be something like:

newMap.Value = v.FirstOrDefault( vitem => vitem.ColumnName == m.ColumnName );

This would give you the first item within "v" that has a "ColumnName" property that matches the "ColumnName" property of "m". This assumes that the contents of "vallist" are objects that have a "ColumnName" property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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