Reputation: 4906
I am having a Cardtable with values
ID Card No
------- ----------
1 | 0001-1234-5678-9001
2 | 0001-1234-5678-9002
3 | 0001-1234-5678-9003
4 | 0001-1234-5678-9004
5 | 0001-1234-5678-9005
Now i want to search in this table using LINQ
with Card No
i.e. 0001-1234-5678-9001
(Using number directly) or 0001123456789001
(Using number without dashes)
Can anyone help in this?
Upvotes: 1
Views: 717
Reputation: 106826
In the comments to the other answers you have indicated that you want to execute the query on the server side. You can do this by converting the card number into a canonical card number which has the format that is used in the database:
String GetCanonicalCardNo(String cardNo) {
if (cardNo.Length == 19)
return cardNo;
if (cardNo.Length != 16)
throw new ArgumentException("Invalid card number.", "cardNo");
return String.Format(
"{0}-{1}-{2}-{3}",
cardNo.Substring(0, 4),
cardNo.Substring(4, 4),
cardNo.Substring(8, 4),
cardNo.Substring(12, 4)
);
}
This function will convert the card number into 0001-1234-5678-9001
.
You can then find a card using code like this:
var canonicalCardNo = GetCanonicalCardNo(cardNo);
var card = Cards.FirstOrDefault(card => card.CardNo == canonicalCardNo);
The predicate used to select the card only contains a string comparision which can be executed on the server side.
Upvotes: 4
Reputation: 148120
You can do it by comparing of condition statements in Enumerable.Where. Replacing the hypen in the CardNumber and variable will make both strings without hyphens and it will address both cases of with and without hyphen numbers.
var result = Cardtable
.Where(c=> c.CardNumber.Replace("-", "") == cardVariable.Replace("-", ""));
Upvotes: 2
Reputation: 1679
List<Cardtable> cardtable = new List<Cardtable>();
cardtable.Add(new Cardtable() { id = 1, cardno = "0001-1234-5678-9001" });
cardtable.Add(new Cardtable() { id = 2, cardno = "0001-1234-5678-9002" });
string search_string = "0001-1234-5678-9002";
var result = from c in cardtable
where c.cardno.Replace("-", "") == search_string.Replace("-", "")
select c;
foreach (Cardtable ct in result)
{
Console.WriteLine("{0}:{1}", ct.id, ct.cardno);
}
Upvotes: 1