如何为2个对象生成唯一的id
本文关键字:唯一 id 对象 2个 | 更新日期: 2023-09-27 18:01:04
我需要为每个循环的2个对象生成相同的id。我需要专门为id做另一个循环吗?一次创建的对象不会超过20个,所以担心碰撞并不是什么大问题。没有任何内容保存到数据库中。
我需要为productsId和Id 生成一个匹配的uid
public class data
{
public int productsId { get; set; }
public string sqft { get; set; }
public string price { get; set; }
}
public class products
{
public int Id { get; set; }
public string product { get; set; }
}
public class LegendModel
{
public string Color { get; set; }
public string Name { get; set; }
public IList<data> Data { get; set; }
public IList<products> Products { get; set; }
}
public class ExportLegendController : ApiController
{
// POST: api/ExportLegend
[HttpPost]
public PDF Post([FromBody]List<LegendModel> legendModel)
{
try
{
var subjectProperty = legendModel[legendModel.Count - 1];
var xEleLegend = new XElement("Legend",
from item in legendModel
select new XElement("item",
new XElement("Name", item.Name),
new XElement("Color", item.Color)
));
// Save the document...
var dt = DateTime.Now.ToString("g").Replace('/', '-').Replace(':', '-');
var filename = string.Format("{0}-{1}.xml", "Legend", dt);
string physicalPath = HttpContext.Current.Server.MapPath("/legendXmls");
string relativePath = Path.Combine(physicalPath, filename).Replace("''", "/");
var pdfName = relativePath;
xEleLegend.Save(pdfName);
var data = new List<data>();
var products = new List<products>();
foreach (var item in subjectProperty.Data)
{
data.Add(new data
{
productsId = item.productsId,
sqft = item.sqft,
price = item.price
});
}
foreach (var item in subjectProperty.Products)
{
products.Add(new products
{
Id = item.Id,
product = item.product
});
};
var xEleProperty = new XElement("Property",
from d in data
join product in products on d.productsId equals product.Id
select new XElement("Points",
new XElement("Sqft", d.sqft),
new XElement("Price", d.price),
new XElement("Product", product.product)
));
使用GUID和加密生成唯一ID
使用GUID:
public string generateID()
{
return Guid.NewGuid().ToString("N");
}
"N"-xxxxxxxxxxxxxxxxxxxxxx(32位(
或
using System.Security.Cryptography; // Import this Dll
public string Get8Digits()
{
var bytes = new byte[4];
var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
uint random = BitConverter.ToUInt32(bytes, 0) % 100000000;
return String.Format("{0:D8}", random);
}