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
45 views
in Technique[技术] by (71.8m points)

c# - How can I check a value is in a range in IList

I have the following code which returns IList<>

var productCodes = await ProductsService.GetAllProductsAsync();

My Model:

public int ProductStartCode { get; set; }
public int ProducEndCode { get; set; }

When create a new product code range, I would like to check the new code doesn't overlap with the existing Product codes

My Product code looks like as follows:

 ProductStartCode  ProductEndCode 
   100001            100003
   100004            100008
   100009            100011

What I am trying to accomplish I need to check,

For example if I enter: 100001, 100002, 100003 are overlapping since they in between 100001 & 100002 range, 
             100004, 100005, 100006, 100007,100008 are also overlapping since they in between 100004 & 100008 range, 
question from:https://stackoverflow.com/questions/65835171/how-can-i-check-a-value-is-in-a-range-in-ilist

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

1 Reply

0 votes
by (71.8m points)

Given a list of ranges, and a possible range to check for overlap, see if the start or end of the possible range is between any of the ranges in the list:

var isOverlapping = productCodes.Any(p => p.ProductStartCode <= possibleStartCode && possibleStartCode <= p.ProductEndCode) ||
                    productCodes.Any(p => p.ProductStartCode <= possibleEndCode && possibleEndCode <= p.ProductEndCode);

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

1.4m articles

1.4m replys

5 comments

56.9k users

...