Home > Net >  How to separate comma separated and where condition in LINQ
How to separate comma separated and where condition in LINQ

Time:11-26

I have a giftcardamounts in database table.

Column contains dollar and comma separated values. There are 40 rows.

Ex:

row 1: giftcardamounts : ($10,$20,$30,$40,$50)
row 2: giftcardamounts : ($100,$200,$30,$40,$50)
row 3: giftcardamounts : ($10,$20,$300,$400,$500)
...etc 

From frontend there is an input is giftcardselectedamount

Ex: giftcardselectedamount=500

Based on this input amount in need to write LINQ query on dollar and comma separated list of Values.

Please help me how to write this.

CodePudding user response:

Like commenters have noted, you should show some effort in reaching to an answer. Also your question isn't quite clear. Are you asking to return the row with a matching amount? If so you can try the following approach, which returns the first row that contains the dollar amount specified:

void Main()
{
    var data = new[] {
        "$10,$20,$30,$40,$50",
        "$100,$200,$30,$40,$50",
        "$10,$20,$300,$400,$500"};

    var giftcardSelectedAmount = 500M;

    var matchingRow = data.FirstOrDefault(x => x
        .Split(',')
        .Any(v => decimal.Parse(v, NumberStyles.Currency) == giftcardSelectedAmount));
        
    Console.WriteLine(matchingRow);
}

I can easily modify this answer to return all matching rows, a count of occurrences, or a count of rows with occurrences. Let me know if you need any of these modifications and I can modify my answer to add these.

  • Related