Note that there are some explanatory texts on larger screens.

plurals
  1. POis there a better way to write this frankenstein LINQ query that searches for values in a child table and orders them by relevance?
    primarykey
    data
    text
    <p>I have a table of Users and a one to many UserSkills table. I need to be able to search for users based on skills. This query takes a list of desired skills and searches for users who have those skills. I want to sort the users based on the number of desired skills they posses. So if a users only has 1 of 3 desired skills he will be further down the list than the user who has 3 of 3 desired skills.</p> <p>I start with my comma separated list of skill IDs that are being searched for:</p> <pre><code>List&lt;short&gt; searchedSkillsRaw = skills.Value.Split(',').Select(i =&gt; short.Parse(i)).ToList(); </code></pre> <p>I then filter out only the types of users that are searchable:</p> <pre><code>List&lt;User&gt; users = (from u in db.Users where u.Verified == true &amp;&amp; u.Level &gt; 0 &amp;&amp; u.Type == 1 &amp;&amp; (u.UserDetail.City == city.SelectedValue || u.UserDetail.City == null) select u).ToList(); </code></pre> <p>and then comes the crazy part:</p> <pre><code>var fUsers = from u in users select new { u.Id, u.FirstName, u.LastName, u.UserName, UserPhone = u.UserDetail.Phone, UserSkills = (from uskills in u.UserSkills join skillsJoin in configSkills on uskills.SkillId equals skillsJoin.ValueIdInt into tempSkills from skillsJoin in tempSkills.DefaultIfEmpty() where uskills.UserId == u.Id select new { SkillId = uskills.SkillId, SkillName = skillsJoin.Name, SkillNameFound = searchedSkillsRaw.Contains(uskills.SkillId) }), UserSkillsFound = (from uskills in u.UserSkills where uskills.UserId == u.Id &amp;&amp; searchedSkillsRaw.Contains(uskills.SkillId) select uskills.UserId).Count() } into userResults where userResults.UserSkillsFound &gt; 0 orderby userResults.UserSkillsFound descending select userResults; </code></pre> <p>and this works! But it seems super bloated and inefficient to me. Especially the secondary part that counts the number of skills found.</p> <p>Thanks for any advice you can give.</p> <p>--r</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload