Reputation: 1455
I have this class Variables
public class Variables
{
public enum DataType
{
INT, CHAR, BOOL, FLOAT
}
public string Name { get; set; }
public DataType Type { get; set; }
public object Value { get; set; }
public Variables(string name, DataType type, object value)
{
Name = name;
Type = type;
Value = value;
}
}
It is also assumed that Name
is unique. And inside another class I have a list of variables, List<Variables>
public void Main()
{
List<Variables> varList = new List<Variables>();
varList.Add(new Variables("x",DataType.BOOL, true));
varList.Add(new Variables("y",DataType.BOOL, false));
varList.Add(new Variables("z",DataType.BOOL, true));
varList.Add(new Variables("a",DataType.INT, 1));
varList.Add(new Variables("b",DataType.INT, 10));
// I need this to convert into LiNQ.
foreach (Variables _x in varList)
{
if (_x.Name == "z")
{
_x.Value = false;
}
}
}
How can I convert foreach
into LiNQ
? I tried .Where
, .Select
but they return IEnumerable
. Is there a LinQ
method that returns only a single value that matches to a given condition? eg,
Variables _var = varList.MethodName(LambDa Expression).....
Upvotes: 1
Views: 77
Reputation: 28980
You can use also First
varList.First(a => a.Name == "z").Value = false;
Upvotes: 1
Reputation: 7105
var variablesInstance = varList.Where(v => v.Name == "z").FirstOrDefault();
if(variablesInstance != null)
{
variablesInstance.Value = false;
}
You can use First instead of FirstOrDefault if you know the thing exists with that name.
Upvotes: 2
Reputation: 1500875
Well you can use Single
:
varList.Single(x => x.Name == "z").Value = false;
That will fail if there's anything other than exactly one match though.
Alternatives are SingleOrDefault
, FirstOrDefault
, First
, LastOrDefault
and Last
. For example, if you expect "0 or 1" results:
var match = varList.SingleOrDefault(x => x.Name == "z");
if (match != null)
{
match.Value = false;
}
Upvotes: 3