Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

c# - Equality comparison between multiple variables

I've a situation where I need to check whether multiple variables are having same data such as

var x=1;
var y=1;
var z=1;

I want to check whether x==1 and y==1 z==1 (it may be '1' or some other value). instead of this, is there any short way I can achieve same such as below

if(x==y==z==1)

Is this possible in C#?

question from:https://stackoverflow.com/questions/3254839/equality-comparison-between-multiple-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

KennyTM is correct, there is no other simpler or more efficient way.

However, if you have many variables, you could also build an array of the values and use the IEnumerable.All method to verify they're all 1. More readable, IMO.

if (new[] { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 }.All(x => x == 1))

Instead of

if(v1 == 1 && v2 == 1 && v3 == 1 && v4 == 1 && v5 == 1 && v6 == 1 && v7 == 1 && v8 == 1 && v9== 1 && v10 == 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...