[英]C# - Comparing a list<t> to a dynamic list
I have a dynamic list我有一个动态列表
var myNames = new List<dynamic>();
Based on some conditions while iterating through my collection, I am adding 2 columns Name and Address to the dynamic list along with some data基于迭代我的集合时的一些条件,我将 2 列名称和地址以及一些数据添加到动态列表中
myNames.Add(new
{
Name = MyCollection[i].<someName>,
Address = MyCollection[i].<someAddress>
});
Now I have a generic list called dbNames which contains a list of Names retrieved from database.现在我有一个名为 dbNames 的通用列表,其中包含从数据库中检索到的名称列表。 My requirement is to iterate through dbNames for 5 times.
我的要求是遍历 dbNames 5 次。 Get the first (occurrence of a) name that exist in dbNames but not in myNames and add it to myNames.
获取存在于 dbNames 但不在 myNames 中的第一个(出现 a)名称并将其添加到 myNames。
Actually I am not able to figure out how to query the collection fetch the list of Names that exist in dbNames but not in myNames.实际上,我无法弄清楚如何查询集合以获取存在于 dbNames 但不在 myNames 中的 Names 列表。 I tried below
我在下面试过
someName = dbNames.Where(d => !((IEnumerable<dynamic>)myNames.Contains(b=> d== (string)b.Name)).FirstOrDefault();
I am getting an error: 'Cannot convert lamda expression to type dynamic and not able to overcome it despite trying in other ways.我收到一个错误:'无法将 lamda 表达式转换为动态类型,尽管尝试了其他方式,但无法克服它。
try something like,尝试类似的东西,
var x=dbNames.Where(p=>!myNames.Select(q=>q.Name).Contains(p)).ToList().Distinct().Take(5);
Add these names to dynamic list myNames
the way you want.按照您想要的方式将这些名称添加到动态列表
myNames
中。
Full Code:完整代码:
public static void Main()
{
List<string> names=new List<string>{"A","xxx","B","C","D","yyy","E","F"};
List<dynamic> dyn=new List<dynamic>();
dynamic person = new ExpandoObject();
person.Name="xxx";
person.Address="ADD";
dynamic person1 = new ExpandoObject();
person1.Name="yyy";
person1.Address="ADD";
dyn.Add(person);
dyn.Add(person1);
var x=names.Where(p=>!dyn.Select(q=>q.Name).Contains(p)).ToList().Distinct().Take(5);
foreach(var n in x)
{
Console.WriteLine(n);
}
}
The Contains() method just does not accept a lambda expression, that's what the error says. contains() 方法只是不接受 lambda 表达式,这就是错误所说的。
You can use Any() instead, and you can omit the Where() expression:您可以使用 Any() 代替,并且可以省略 Where() 表达式:
someName = dbNames.FirstOrDefault(dbName => !(myNames.Any(b => dbName == b.Name));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.