EF linq在列表中查找objectA.prop1是objectB.prop2中的任何一个

时间:2015-05-06 11:28:42

标签: c# linq entity-framework contains any

我对linq查询有一些疑问,我无法做到。找到对象的问题

考虑List(ListA),其中我想选择字段F20的值在列表中的所有行(ListB)。对于这些项目中的每一项,我将替换"搜索的值"通过它"替换值"。

//StringReplacer(SearchValue,ReplacementValue)
List<StringReplacer> ListB = new List<StringReplacer>(); 
ListB.Add(new StringReplacer("JAN", "24/01/2015"));
ListB.Add(new StringReplacer("FEB", "24/02/2015"));
ListB.Add(new StringReplacer("MAR", "24/03/2015"));
ListB.Add(new StringReplacer("APR", "24/04/2015"));


List<XLS2015> ListA = new List<XLS2015>();
ListA = db.XLS2015.Where(y => (ListB.Any(y.F20.Any(tt => tt.SearchValue.Contains)))).ToList();

ListA = db.XLS2015.Where(y => (ListB.Any(y.F20.Contains(tt => tt.Source)))).ToList();

我可以用foreach做到这一点,但我认为linq声明可以做得更好。

我在ListB is List`:

时已经实现了这一目标
ListA = ListA.Where(c => (ListB.Any(c.F20.ToString().Contains))).ToList();

但我无法弄清楚如何处理对象的属性...

作为一个额外的问题,不是搜索值(Any()Contains()),而是有任何函数可以&#34; SearchAndReplace&#34;一枪?

1 个答案:

答案 0 :(得分:1)

您只能在数据库端选择,并在.NET端替换。您仍然可以在单个LINQ查询中执行此操作,但它只能在SQL上执行。

你可以试试这个:

// To make it easier to create sql query put all search string in array
string[] search = ListB.Select(b => b.Search).ToArray();

List<XLS2015> ListA = db.XLS2015
    .Where(a => search.Contains(a.F20))
    .AsEnumerable() // execute on server at this point, and do rest in C#

    .Join(ListB, a => a.F20, b => b.Search, (a, b) => new { A = a, B = b })
    .Select(x => {
        // do replacement
        x.A.F20 = x.A.F20.Replace(x.B.Search, x.B.Replacement);
        return x.A;
    })
    .ToList();