Error in lambda: No implicit convertion between - c#

I convert one list of to list and get error:
"Type of conditional expression cannot be determined because there is no implicit conversion between System.Collections.Generic.List and 'void'
return (topics.Select(c => new TopicUi()
{
Bookmarks = new List<Bookmark>().Add(new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName })
})).ToList();
Why?

The Add method of List has a return type of void, this should work for you:
return (topics.Select(c => new TopicUi
{
Bookmarks = new List<Bookmark> {
new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName }
}
})).ToList();

At the very leat, fix this line
Bookmarks = new List<Bookmark>().Add(new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName })
Add is a void returning method. The line should be
Bookmarks = new List<Bookmark> { new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName } }
In order to properly use collection initialization.

Rather than calling the Add method of List<T>, you can just use the object initialization syntax:
return (topics.Select(c => new TopicUi()
{
Bookmarks = new List<Bookmark>()
{ new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName } }
)
})).ToList();

IList.Add has no return type. Try this;
Func<YourCType, IList<Bookmark>> createBookmarkListFunc = (c) =>
{
var list = new List<Bookmark>() { new Bookmark { Id = c.BookmarkId, Name = c.BookmarkName };
return list;
});
return (topics.Select(c => new TopicUi()
{
Bookmarks = createListFunc(c)
})).ToList();

Related

Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable<string>when using Nest to search a text

I am having a code error "Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable" when trying to use Nest to search a text
class Program
{
static void Main(string[] args)
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.DefaultIndex("my_index");
var client = new ElasticClient(settings);
var text = "testinsg, test, my testing";
var analyzeResponse = client.Indices.Analyze(new AnalyzeRequest
{
// error occurred here when trying to pass the value of the variable text
Text = text,
Analyzer = "standard",
Tokenizer = "standard"
});
var stemmedWords = analyzeResponse.Tokens.Select(t => t.Token);
var stemCounts = stemmedWords
.GroupBy(w => new Stemmer().Stem(w))
.Select(g => new { Stem = g.Key, Count = g.Count() })
foreach (var stemCount in stemCounts)
{
Console.WriteLine($"Stem: {stemCount.Stem}, Count: {stemCount.Count}");
}
}
}
Seems that Text is IEnumerable<string> so just wrap the string into collection, for example array:
new AnalyzeRequest
{
Text = new [] {text},
// ...
}

Adding to list<objcect> with foreach loop

Is it possible something like this? I've worked hard, but I think it's not possible, I hope someone will help me.
I have to fill the object like this,
var obj = new
{
parentObj = new List<object>()
{
outsideArray.ForEach(x=>
{
})
}
}
I dont like this.
var obj = new
{
parentObj= new List<object>()
{
new object() { bla, bla }
}
}
I want to do.
var obj {
Id =1,
Name= "any",
Address = new {
userAddressList.forEach(x=> {
Town = x.town,
State = x.state
}
}
}
The code in the second and third code snippets does not comply to C# syntax.
However, you may use LINQ to fill your array nicely similar to what shown in the third snippet:
var obj = new
{
Id = 1,
Name = "any",
Address = userAddressList.Select(x =>
{
Town = x.town,
State = x.state
})
};

C# exclude duplicate code from two method returning expression

I have two functions, returning expression translated to EF.:
public static Expression<Func<TripLanguage, TripViewModel>> ToSearchModel(ILookup<int, TagViewModel> tags)
{
return tripLanguage => new TripViewModel()
{
From = tripLanguage.From,
To = tripLanguage.To,
Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
Level = tripLanguage.Trip.Level,
BicycleType = tripLanguage.Trip.BicycleType,
UrlId = tripLanguage.UrlId,
Distance = tripLanguage.Trip.Distance,
Tags = tags[tripLanguage.TripId], //This is only different and in function args of course
MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
{
Filename = i.Filename,
Id = i.Id,
Title = i.Title
}).Take(1)
};
}
public static Expression<Func<TripLanguage, TripViewModel>> ToSearchModel()
{
return tripLanguage => new TripViewModel()
{
From = tripLanguage.From,
To = tripLanguage.To,
Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
Level = tripLanguage.Trip.Level,
BicycleType = tripLanguage.Trip.BicycleType,
UrlId = tripLanguage.UrlId,
Distance = tripLanguage.Trip.Distance,
MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
{
Filename = i.Filename,
Id = i.Id,
Title = i.Title
}).Take(1)
};
}
The only different is Tags collection. Is possible something like call method, without arguments and add Tags attribute which exclude duplicate code? Or Use some inheritance expression?
Thank you for your time.
Change the first method to work with null tags, and provide a null default for it:
public static Expression<Func<TripLanguage,TripViewModel>> ToSearchModel(ILookup<int, TagViewModel> tags = null) {
return tripLanguage => new TripViewModel() {
From = tripLanguage.From,
To = tripLanguage.To,
Annotation = tripLanguage.Description.Truncate(Strings.TRUNCATE_ANOTATION),
Level = tripLanguage.Trip.Level,
BicycleType = tripLanguage.Trip.BicycleType,
UrlId = tripLanguage.UrlId,
Distance = tripLanguage.Trip.Distance,
Tags = tags?[tripLanguage.TripId], // <<== Note the question mark
MainImage = tripLanguage.Trip.Images.OrderBy(s => s.Date).Select(i => new ImageViewModel
{
Filename = i.Filename,
Id = i.Id,
Title = i.Title
}).Take(1)
};
}

Cannot implicitly convert type 'System.Linq.IQueryable?

here is my code which is giving me above error
public ActionResult Edit(int id = 0)
{
KBS_Virtual_TrainingEntities db = new KBS_Virtual_TrainingEntities();
UsersContext ctx = new UsersContext();
UserProfile model = ctx.UserProfiles.Find(id);
List<CourseSubscription> user_Course_subscriptions = new List<CourseSubscription>();
foreach (UserSubscription sub in db.UserSubscriptions)
{
if (sub.ID == id)
{
user_Course_subscriptions.Add(sub.CourseSubscription);
}
}
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);
var coursesList = from courses in not_subscribe
select new SelectListItem
{
Text = courses.Course.Name,
Value = courses.Course.ID
.ToString()
};
var CoursesTYPE = from CourseTypes in db.CourseTypes.ToList()
select new SelectListItem
{
Text = CourseTypes.Name,
Value = CourseTypes.ID
.ToString()
};
ViewBag.CourseID = coursesList;
ViewBag.type = CoursesTYPE;
return View(model);
}
I am trying to find Course Subscription that are not subscribe by the current user by using the above code but its not working?
You're missing ToList on the results from your Except function. Do a ToList like so:
List<CourseSubscription> not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions).ToList();
Or since in your code you're not doing anything that needs a list, simply var it or assign the correct type to it such as IQueryable<CourseSubscription> to it.
var not_subscribe = db.CourseSubscriptions.Except(user_Course_subscriptions);

IQueryable, converting Anonymous Type to Strong Type

Is there a more elegant/concise way of this; I'd like to get rid of foreach loop with the WorkListItem initialization code.
var queryable = registrations.Select(
r => new
{
r.Id, r.AccountNumber, r.DateAdded, r.DateUpdated, r.Patient, r.Patient.InsuranceInfos
});
var list = queryable.ToList();
var workListItems = new List<WorkListItem>();
foreach (var anonymous in list)
{
var w = new WorkListItem
{
Id = anonymous.Id,
ClientAccountId = anonymous.AccountNumber,
DateAdded = anonymous.DateAdded,
DateUpdated = anonymous.DateUpdated,
Patient = anonymous.Patient,
InsuraceInfos = anonymous.Patient.InsuranceInfos
};
workListItems.Add(w);
}
return workListItems;
Yes you can completely cut out the "middle-man" as it were and select straight into a new WorkListItem as below:
var list = registrations.Select(r => new WorkListItem
{
Id = r.Id,
ClientAccountId = r.AccountNumber,
DateAdded = r.DateAdded,
DateUpdated = r.DateUpdated,
Patient = r.Patient,
InsuraceInfos = r.Patient.InsuranceInfos
}).ToList();

Categories