开发者

Using Linq to Entities to find the best match in table

开发者 https://www.devze.com 2023-01-22 23:43 出处:网络
I have a table with two columns that will be used as filtering criteria. Using Linq to Entities, I want to pass in two values and always return the closest match. For example, (1,2) should return (1,2

I have a table with two columns that will be used as filtering criteria. Using Linq to Entities, I want to pass in two values and always return the closest match. For example, (1,2) should return (1,2) not (null,2) as the closest. If neither value finds a match, then the Null, Null column match is used.

Below is the sample code.

If 3,3 is passed in the first Data (null,null) should be returned since there are no matches.

If 1,3 is passed in , the second Data (1,null) should be returned.

If 3,2 is passed in , the third Data (null,2) should be returned.

If 1,2 is passed in, the fourth Data(1,2) should be returned.

Is this possible to do in one Linq query since it is generating a database hit?

public class Data
        {
            public string prop1 { get; set; }
            public  string prop2 { get; set; }
        }

        static void Main(string[] args)
        {
            List<Data> datas = new List<Data>
                                   {
                                       new Data
                                           {
                                               prop1 = null,
                                               prop2 = null
                                         开发者_如何学JAVA  },
                                       new Data
                                           {
                                               prop1 = "1",
                                               prop2 = null
                                           },
                                       new Data
                                           {
                                               prop1 = null,
                                               prop2 = "2"
                                           },
                                       new Data
                                           {
                                               prop1 = "1",
                                               prop2 = "2"
                                           }
                                   };


        }


Could simply do something like

    Data def = new Data { prop1 = null, prop2 = null };
    var result = (from d in datas
                  where d.prop1 == value1 || d.prop2 == value2
                  orderby (d.prop1 == value1 ? 8 : 0) + (d.prop2 == value2 ? 4 : 0) + (d.prop1 == null ? 2: 0) + (d.prop2 == null ? 1 : 0) descending
                  select d).FirstOrDefault() ?? def;

where value1 and value2 are the 2 string to search for, should run as 1 query (didn't test)

0

精彩评论

暂无评论...
验证码 换一张
取 消