Click here to Skip to main content
15,867,834 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a List "_DataInfo" i need to filter it with only those id's which is in the string "_id", please help me to write a query using linq to get the result.


C#
string _id = "111,222,333";

_DataInfo.Where(x => x.ID == _id);
Posted
Updated 23-Dec-15 3:55am
v2
Comments
Midi_Mick 23-Dec-15 9:20am    
Are you looking for x.ID == "111,222,333" or x.ID == "111" or "222" or "333". If the former, then you already have it right. If the latter, then you could do something like

_DataInfo.Where(x=> _id.Split(',').Contains(x.ID));
[no name] 23-Dec-15 9:28am    
Thank you contains worked :)
Dave Kreskowiak 23-Dec-15 9:57am    
Copy this into a solution so this question drops off the unanswered list.
Suvendu Shekhar Giri 23-Dec-15 10:14am    
Please add it as solution.

Are you looking for x.ID == "111,222,333" or x.ID == "111" or "222" or "333". If the former, then you already have it right. If the latter, then you could do something like

C#
_DataInfo.Where(x=> _id.Split(',').Contains(x.ID));
 
Share this answer
 
Comments
BillWoodruff 23-Dec-15 11:34am    
+5 good code !

One possible suggestion: define the split _id outside the Linq query: I think this might prevent the split from being invoked more than once ... but, I am not absolutely certain of this, given the optimizations that Linq does when it creates an IEnumerable ... as is the case here.

cheers, Bill
George Swan 24-Dec-15 14:38pm    
You are quite right with your suggestion, Bill. This is much quicker
var ids = _ids.Split(',');
var result=_DataInfo.Where(ids.Contains);
Midi_Mick 24-Dec-15 15:13pm    
Interesting. The optimising compiler obviously isn't as good as it really should be. I'll keep that sort of thing in mind when writing my own time critical code.
Another option is to use Any[^] method but it depends on what you want to achieve. I'd suggest to read about Except[^] and Contains[^] methods.

Take a look at this example (using LinqPad):
C#
void Main()
{
	
	List<DataInfo> _DataInfo = new List<DataInfo>();
	
	Random r = new Random();
	for (int i = 0;i<30;i++)
	{
		_DataInfo.Add(new DataInfo(r.Next(100, 350)));
	}

	string _id = "111,222,333";
	var ids = _id.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries).Select(x=>Convert.ToInt32(x));

	var result = _DataInfo.Where(x => ids.Any(y=> y == x.ID));
	//result.Dump();
}

// Define other methods and classes here
public class DataInfo
{
	private int id = 0;
	
	public DataInfo(int _id)
	{
		id = _id;
	}
	
	public int ID
	{
		get { return id; }
		set { id = value; }
	}
	
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900