检查数据库中的字符串以查看它是否包含数组中的项

时间:2012-01-30 14:06:55

标签: c# linq-to-sql arrays

最好的方法是什么?我现在有这个代码,但它不起作用。

 if (db.tblOrganizations.Where(x => (
             new string[7] { "A1", "A2", "A3", "A4", "A5", "A6", "SG" }
         ).Contains(x.strAcronym.ToUpper().Trim()))
     .Select(x => x.guidOrgId)
     .Where(x => x == guidCustOffice)
     .Any())

我真正需要做的是检查数据库中的首字母缩写词是否包含任何字符串数组,如果首字母缩略词是A1O,那么由于字符串中的A1项目,它仍将属于该类别[ ]

2 个答案:

答案 0 :(得分:1)

如果您使用的是Sql Server 2008,您可以探索的另一个选项是Table Valued parameters

以下示例(来自Plamen Ratchev的改编示例)展示了如何在Sql server中使用Table值params

您可以在数据库中使用以下内容:

-- User-defined table type
CREATE TYPE LookupCodeTable
AS TABLE (
 lookupcode varchar(10)
)
GO     

-- Procedure with table valued parameter
-- Must use the READONLY clause
CREATE PROCEDURE SelectLoansByCodes
  @lookupCodes LookupCodeTable READONLY
AS
  Select * from Loans 
  inner join @lookupCodes l on Loans.loancode like l.lookupcode + '%'

GO

这是来自sql server的示例用法

-- Sample usage from Sql Server
CREATE TABLE Loans (
 loan_nbr INT PRIMARY KEY,
 loancode varchar(50),
 loan_amount DECIMAL(15, 2));


-- Initialize the table variable with data
INSERT INTO Loans
VALUES (1, 'A120080101', 10000.00),
       (2, 'A120080203', 15000.00),
       (3, 'A220080315', 25000.00),
       (4, 'A120080101', 30000.00),
       (5, 'A320080203', 45000.00),
       (6, 'A520080315', 55000.00);

GO 


DECLARE @myLookupcodes LookupCodeTable;

-- Initialize the table variable with data
INSERT INTO @myLookupcodes
VALUES ('A1'), ('A2'), ('A5')

EXEC SelectLoansByCodes @lookupCodes = @myLookupCodes;

来自您的应用程序的示例用法:

var loans = new DataTable();
loans.Columns.Add("lookupcode", typeof(string), 10);
using(SqlCommand cmd = new SqlCommand("SelectLoansByCodes", conn)
{
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("Loans", loans);
      SqlDataReader reader =
        cmd.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine(String.Format("{0}, {1}, {2}", reader[0], reader[1], reader[2]));
    }
}

和使用表值参数(带函数)和实体框架的指针:

http://blogs.msdn.com/b/efdesign/archive/2009/01/07/model-defined-functions.aspx

答案 1 :(得分:-2)

**

BAH,不工作。忽略。

**

好的,这是我的答案。我在这里做的是根据你的首字母缩略词列表中最长的缩写词确定要比较的字符数。因此,使用您的示例,我正在检查数据库结果的前两个字符,因为最大大小的首字母缩写是两个字符长。

var acronymList = new List<String> { "A1", "A2", "A3", "A4", "A5", "A6", "SG", };
var dbResult = "A10"; // get this from your database call.

var charsToCheck = acronymList.Max(x => x.Length);

if (charsToCheck > dbResult.Length)
     charsToCheck = dbResult.Length;

var trimmedDbResult = dbResult.Substring(0, charsToCheck);

var foundAcronym = acronymList.SingleOrDefault(acronym => acronym == trimmedDbResult);

if (foundAcronym != null)
{
     // use the found acronym
     Response.Write(foundAcronym); // prints "A1" in this example.
}

else
{
     // acronym not found, handle error
     Response.Write("error");
}