LINQ with ref parameter
-
Hi, I'd like to know if it's possible to get a collection of something with LINQ with the 'where' clause equal to a function that has a ref parameter.
var objCol = from id in ids
where id.GetValue(2, ref strValue) == "6"
select id;The result should be based on the ref value. Thanks
-
Hi, I'd like to know if it's possible to get a collection of something with LINQ with the 'where' clause equal to a function that has a ref parameter.
var objCol = from id in ids
where id.GetValue(2, ref strValue) == "6"
select id;The result should be based on the ref value. Thanks
It certainly is possible. Here's a little sample for you to try:
public class LinqTester
{
public void Test()
{
LinqCollection collection = new LinqCollection(
List<LinqItem> values = collection.Where(x =>
{
string value = string.Empty;
x.GetValue(6, ref value);
return value == "6";
}).ToList();// Should have one value here - you can do something with it now.
}
}public class LinqCollection : List<LinqItem>
{
public LinqCollection()
{
for (int i = 0; i < 10; i++)
{
this.Add(new LinqItem { Id = i });
}
}
}public class LinqItem
{
public int Id { get; set; }
public void GetValue(int item, ref string value)
{
value = Id.ToString();
}
}This space for rent
-
Hi, I'd like to know if it's possible to get a collection of something with LINQ with the 'where' clause equal to a function that has a ref parameter.
var objCol = from id in ids
where id.GetValue(2, ref strValue) == "6"
select id;The result should be based on the ref value. Thanks
Well, you can, as Pete showed you. But it's not really a good idea, and probably won't work as you want it to. It would be better to change the method so that it doesn't use a
ref
orout
parameter. If you can't change it, then write a wrapper method. You can either return a specific type to encapsulate the two returned values, or use a Tuple[^]. In C#7, there will even be built-in language support for tuples[^], which will make this much easier.static class YourExtensions
{
// NB: In this case, a specific type would be better, since it's not
// immediately obvious which tuple item represents which value.public static Tuple<string, string> GetValue(this YourType id, int theParameter) { string strValue = null; string result = id.GetValue(theParameter, ref strValue); return Tuple.Create(result, strValue); }
}
...
var objCol = from id in ids
let value = id.GetValue(2)
where value.Item1 == "6"
select new { id, strValue = value.Item2 };
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer