Pergunta

I have a simple Raven dB table which is as follows:

char[] colorArray= colorValue.ToCharArray().Distinct().ToArray();

for loop{
var entity = new Color { ID = id, colorArray = colorArray };
session.Store(entity);
}
Session.Savechanges();

This table consists of 1000 or more records.


Now user inputs an array:

char[] userinput=userinput.tocharArray().Distinct().ToArray();

Suppose user's array consists of characters 'r', 'e' and 'd'. I need to list all records which consists of all user inputted characters (i.e. the output records needs to have 'r', 'e' and 'd' characters).

I tried different techniques including following:

.Where(x=>x. colorArray.Intersect(userinput).Count()==userinput.count())

But not working, giving following error: Cannot understand how to translate x.subsetArray.Intersect…

Foi útil?

Solução

The Array intersection is not allowed, but you can write your query as follows:

var colors = session.Query<Color>()
                    .Where(c =>
                            c.colorArray.Any(x => x == "r") &&
                            c.colorArray.Any(x => x == "e") &&
                            c.colorArray.Any(x => x == "d"));

Please note that in order for this to work, you need to use strings, not chars. The colorArray property in your Color class needs to be defined as:

public string[] colorArray { get; set; }

The reason is that if you use char[], then the query will check for the numeric values (ASCII codes) rather then the string values (ex: 'r' will be interpreted by the query engine as 114, 'e' to 101 and 'd' to 100).

Now, to take this to the next step and make the query condition dynamic, with respect to the userInput string array:

var userInput = new[] {"r", "e", "d"};

var colors = session.Query<Color>();

// dynamically add a WHERE clause for each letter in the array
foreach (var letter in userInput)
{
    var currentLetter = letter;

    colors = colors.Where(c => c.colorArray.Any(x => x == currentLetter));
}

// display the results
foreach (var color in colors)
    Console.WriteLine(color);

This should produce the results you expect: the documents that have "r", "e" and "d" in their colorArray.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top