开发者

how do I find a list of integers in a generic list<T>

I have a list of integers and a list of objects (Class_A) with integers as an identifier. what would be a good way to create a list of objects (Class_A) based on the ids in the integer list.

I get stuck at:

List<class_A> list =  A开发者_JS百科_List.FindAll(delegate(class_A tmp) 
                      { return ids.Contains(tmp.ID); });


 void main()
  {
  List<int> ids = new List<int>();
  ids.Add(1);
  ids.Add(3);
  ids.Add(5);

  List<class_A> A_List = new List<class_A>();
  A_List.Add(new class_A(1, "one"));
  A_List.Add(new class_A(2, "two"));
  A_List.Add(new class_A(3, "three"));
  A_List.Add(new class_A(4, "four"));
  A_List.Add(new class_A(7, "seven"));
}

 public class class_A
 {
public int ID { get; set; }
public string Text { get; set; }
public class_A( int id,string text)
{
  Text = text;
  ID = id;
}
}


Looks like a join to me:

var query = A_List.Join(ids, x => x.ID, y => y, (x, y) => x)
                  .ToList();

Or in query expression format:

var query = (from a in A_List
             join id in ids on a.ID equals id
             select a).ToList();

If you don't actually need a List<T>, but an IEnumerable<T> is fine for you (e.g. you're just iterating over it once), just leave off the ToList() call.

That's assuming you have LINQ available to you. If you don't have LINQ or C# 3, you could use:

List<A> matches = A_List.FindAll(delegate(A a) { return ids.Contains(a.ID); });


Non-optimized version:

var instancesOfAInList = ids.Where(id => A_List.Any(a => a.ID == id));


A_List.Where(c => ids.Contains(c.ID));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜