代码之家  ›  专栏  ›  技术社区  ›  David Carek

Linq to Entities:其中包含1个值和许多列

  •  0
  • David Carek  · 技术社区  · 5 年前

    我知道在sql中你会做这样的事情

    WHERE 'val' IN (field1, field2, field3, field4, ...)
    

    我想知道是否有一种方法可以使用Linq对实体进行类似的操作?我现在唯一能想到的是创建一个巨大的“或”字段语句,我想搜索如下

    .where(m => 
        m.field1.Contains('val') ||
        m.field2.Contains('val') ||
        m.field3.Contains('val') ||
        m.field4.Contains('val'));
    

    有没有一个更干净的方式来写这个搜索,还是我有什么好,因为它得到了?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Jonhyfun    5 年前

    您没有正确使用Contains(),如 Theodor Zoulias ,因为在on-SQL中检查相等性,而contains则类似于on-SQL。另外,您还用 ' " , ' 只适用于单个字符。

    假设你试图在任何财产都有一定价值的地方重审“m”,你将不得不使用 :

    public bool FieldSearch(object a, string b)
    {
      //Get the type of your object, to loop through its properties
      Type t = a.GetType();
      //loop and check (the loop stops once the first property that matches has been found!)
      foreach(PropertyInfo p in t.GetProperties())
      {
        if(p.GetValue(a).ToString()==b)
        {
        return true;
        }
      }
      return false;
    }
    

    小心 ,可能需要添加BidingAttributes,因为它检索 (公共)财产。

    现在只需在linq上使用新的bool方法:(根据上下文来考虑性能不是一个好主意)

    .where(m => FieldSearch(m,"val"))
    

    尽管所有这些都是可能的,但你可能有一个 架构问题

    也许有更好的方法来做你想做的事。。

        2
  •  0
  •   colinD Andrey K47    5 年前

    你可以的

    .Where(f => new string[] { f.field1, f.field2, f.field3 }.Any(s => s.Contains("val")));
    

    有你发布的代码的行为,或者

    .Where(f => new string[] { f.field1, f.field2, f.field3 }.Contains("val"));
    

    检查是否相等。

    但我不能说这是不是一个好的表现。

    下面是一个代码示例:

    public class ClassWithFields
    {
        public int Id { get; set; }
        public string Field1 { get; set; }
        public string Field2 { get; set; }
        public string Field3 {get;set;}
    }
    
    
    public class Program
    {
        public static void Main()
        {
            var listFields = new List<ClassWithFields>()
            {
                    new ClassWithFields { Id = 1, Field1 = "val", Field2 = "qewr", Field3 = "asdqw" },
                    new ClassWithFields { Id = 2, Field1 = "asdf", Field2 = "asdd", Field3 = "asdqw" },
                    new ClassWithFields { Id = 3, Field1 = "asdf", Field2 = "qewr", Field3 = "qwvaleqwe" }
            };
    
            var containsVal = listFields.Where(f => new string[] { f.Field1, f.Field2, f.Field3 }.Any(s => s.Contains("val")));
            var equalsVal = listFields.Where(f => new string[] { f.Field1, f.Field2, f.Field3 }.Contains("val"));
        }
    }
    

    你可以在 https://dotnetfiddle.net/lXSoB4