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).....
Well you can use
Single:That will fail if there’s anything other than exactly one match though.
Alternatives are
SingleOrDefault,FirstOrDefault,First,LastOrDefaultandLast. For example, if you expect “0 or 1” results: