I have a class:
开发者_运维问答public class MyObject
{
public string Code;
public string FullName;
}
I have a List of Myobject objects:
Code FullName
"ABC" "The abc company"
"BBC" "The bbc company"
"CPA" "The cpa company"
My requirement: a matched condition is a Code or FullName contains input word. With matched records, I will sort on Code before and FullName later.
Example:
When user input a string: "bc", return a list:
Code FullName
"ABC" "The abc company"
"BBC" "The bbc company"
When user input a string: "pa", return this list (note that "PA"
is part of the Code, so it is displayed first):
Code FullName
"CPA" "The cpa company"
"ABC" "The abc company"
"BBC" "The bbc company"
Explain: When sorting, the Code field is more Priority than FullName field. Because, all of records contains the string "pa" but only the record with Code "CPA" contain "pa", so it must be above.
PS: I'm using .NET 2.0/C# 2.0. String compare in filtering is not case-sensitive.
I'd do the following:
- create an array of integers that has the same length as your array of companies
- iterate over all the companies
- test to see if the company code starts with user input, if yes, add 1000 to the int array at the current index.
- test to see if the company code contains the user input, if yes, add 100 to the int array at the current index
- test to see if the company fullname contains the user input, if yes, add 10 to the int array at the current index.
- (add additional tests, in my string search system I ended up having 7 distinct matchings)
- sort the company array using the int array as keys
- return the first N results from the sorted array, or all results, or all results that have a key larger than 0.
Maybe something like this:
var filtered = myObjList.Where(p=> p.Code.Contains(searchTerm) || p.FullName.Contains(searchTerm))
var sorted = filtered.OrderBy(p=> p.Code.StartsWith(searchTerm) ? 1 : 0).ThenBy(p=> p.FullName.StartsWith(searchTerm) ? 1 : 0)
It's simplistic, but you can play with it to get the results you want.
精彩评论