2009-12-03 98 views
1

在C#ASP.Net MVC项目中,我试图从LINQ变量中创建一个List> < string>。LINQ变量不使用列名称的字符串列表?

现在这可能是一个非常基本的东西,但我不能在没有为该变量中的数据使用实际列名称的情况下工作。问题在于,为了尽量使程序尽可能动态化,我将其放到存储过程中以获取数据。可以有任何数量的任何方式命名的列,这取决于从中获取数据的位置。我所关心的是将所有值写入List> < string>,以便我可以在程序中比较用户输入的值。

在代码中指向列的名称意味着我不得不做几十个重载的方法,所有这些方法基本上都做同样的事情。以下是虚假的无功能代码。但它应该打开我的意思。

 
// call for stored procedure 
var courses = db.spFetchCourseInformation().ToList(); 

// if the data fails a check on a single row, it will not pass the check 
bool passed = true; 

foreach (var i in courses) 
{ 
    // each row should be cast into a list of string, which can then be validated 
    // on a row-by-row basis 
    List courseRow = new List(); 
    courseRow = courses[i]; // yes, obviously this is wrong syntax 
    int matches = 0; 
    foreach (string k in courseRow) 
    { 
     if (validator.checkMatch(courseRow[k].ToString())) 
     { 
     matches++; 
     }      
    } 
    if (matches == 0) 
    { 
     passed = false; 
     break; 
    } 
} 

现在下面是我现在怎么也得做,因为我需要使用的名称为列

 
for (int i = 0; i < courses.Count; i++) 
{ 
    int matches = 0; 

    if (validator.checkMatch(courses[i].Name)) 
     matches++; 

    if (validator.checkMatch(courses[i].RandomOtherColumn)) 
     matches++; 

    if (validator.checkMatch(courses[i].RandomThirdColumn)) 
     matches++; 

    if (validator.checkMatch(courses[i].RandomFourthColumn)) 
     matches++; 

    /* etc... 

     * etc... 
     * you get the point 
     * and one of these for each and every possible variation from the stored procedure, NOT good practice 
     * */ 

感谢您的帮助的例子!

回答

0

我不是100%确定你想要解决什么问题(将用户数据与数据库中的特定记录进行匹配?),但我确信你正在以一种错误的方式去解决这个问题。将数据放入List中。我

吨应该有可能得到您的用户输入在一个IDictionary与密钥用于列名称和对象作为输入数据字段。

然后,当您从SP获取数据时,您可以将数据返回到DataReader(一个la http://msmvps.com/blogs/deborahk/archive/2009/07/09/dal-access-a-datareader-using-a-stored-procedure.aspx)。

DataReaders按列名进行索引,因此如果您通过输入数据IDictionary中的键运行,则可以检查DataReader以查看它是否具有匹配的数据。

using (SqlDataReader reader = Dac.ExecuteDataReader("CustomerRetrieveAll", null)) 
{ 
    while (reader.Read()) 
    { 
     foreach(var key in userInputDictionary.AllKeys) 
     { 
     var data = reader[key]; 
     if (data != userInputDictionary[key]) continue; 
     } 
    } 
} 

仍然不确定您正在解决的问题,但是,我希望这有助于您!

+0

我试图解决的问题是,项目创建时尽可能动态,考虑到未来的更新。目前存储过程访问一个表。将来,该过程将根据作为参数传入的用户类型,完全从不同的表中获取数据。但无论过程中使用哪个表,代码的最终目标都保持不变:查看是否有任何行的值与验证程序中的值相匹配。 – Kahn 2009-12-03 12:39:22

0

有点创意的反思应该做的伎俩。

var courses = db.spFetchCourseInformation() 
var values = courses.SelectMany(c => c.GetType().GetProperties() // gets the properties for your object 
        .Select(property => property.GetValue(c, null))); // gets the value of each property 
List<string> stringValues = new List<string>(
       values.Select(v => v == null ? string.Empty : v.ToString()) // some of those values will likely be null 
       .Distinct()); // remove duplicates