开发者

linq query for selecting from one list based on another

public class Test
{
  int i;
  string s;
}

List<Test> testList = new List<Test>(); //assume there are some values in it.

List<int> intList = new List<int>(){ 1,2,3};

How to开发者_如何学Python I say get items from testList where i is in intList using the linq to objects.

something like List<Test> testIntList = testList.Where(t=>t.i in intList)


Technically, it would be:

List<Test> testIntList = testList.Where(t => intList.Contains(t.i)).ToList();

However, that might be slow if intList is large, since List<T>.Contains performs its search in O(n). A faster approach would be to use a HashSet<T>:

HashSet<int> intList = new HashSet<int>(){ 1,2,3 };


This would also be interesting and would perform well:

List<test> finalList = testList.Join(intList, 
                                     test => test.id,
                                     i => i,
                                     (t, i) => t).ToList();

You know when you join tables in a SQL SELECT? This is how to do it using Linq to Objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜