Home > Software engineering >  How to use an unknown number of queries?
How to use an unknown number of queries?

Time:09-23

Let's assume that I have a List of playing card objects whose values are stored in a delimited string containing the value, suit, and color. Eg. "king:heart:red" Admittedly, a bad design choice but just go with it for the purpose of the question.

I could write the following linq queries:

var result = from c in cards
    where c.Contains("king")
    select c;

var result = from c in cards
    where c.Contains("king")
    where c.Contains("red")
    select c;

var result = from c in cards
    where c.Contains("king")
    where c.Contains("queen")
    where c.Contains("jack")
    select c;

The first one would return the four kings The second would return the two red queens And the third would return all 12 picture cards.

What if the where.Contains queries were based on user input and could have many more options?  How would I write the code to deal with an unknown number of where.Contains queries?

CodePudding user response:

Out of the top of my head something like this would be possible with entity framework:


var inPut = new List<string> { "king", "red", "jack" };

var result = from c in cards
    where inPut.Any(x => c.Contains(x))
    select c;

CodePudding user response:

You could pass the parameters from the user in the List and do something like this:

List<Cards> cardsToReturn = new(); 
foreach(var item in UserInput)
{
    cardsToAdd = cards.Where(x => x.Contains(item)).ToList(); 
    cardsToReturn = (List<Cards>)cardsToReturn.Concat(cardsToAdd);
}

CodePudding user response:

try this

    var cards= new string[] { "king:red:jack", "king:heart:red" };
    
    var strArray = new string[] { "heart" };

    var result = GetCards(cards,strArray);

public IEnumerable<string> GetCards(string[] cards,  string[] strArray)
{
    return cards.Where(c=> IfContains(c,strArray)).ToArray();
}

public bool IfContains(string card, string[] strArray)
{
    var cardArray =card.Split(":");
    return cardArray.Any(c => strArray.Contains(c));
}

test result

[ "king:heart:red" ]

or if you have string from an user input

var input="king,red";
var strArr=input.Split(',');
var result=GetCards(cards,strArr);

test result

[ "king:heart:red","king:red:jack"]
  • Related