简体   繁体   中英

Check a string in the database to see if it contains an item in an array

What is the best way to do this? I have this code now, but it is not functional.

 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())

really what I need to do is check to see if the acronym from the database contains any of the string array, that way if the acronym is A1O then it will still fall into the category due to the A1 item in the string[].

In case you are using Sql Server 2008, another option you could explore is Table Valued parameters

The following sample (adapted example from Plamen Ratchev ) shows how you could use Table valued params in Sql server

You could use the following in the database:

-- 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

This is sample usage from 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;

And sample usage from your application:

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]));
    }
}

and a pointer on using table valued parameters (with functions) with Entity framework:

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

**

BAH, not working. Ignore.

**

OK here's my answer. What I am doing here is determining how many characters to compare based on the longest sized acronym in your acronym list. So using your example, I am checking the first two chars of the database result, because the max sized acronym is two chars long.

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");
}

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